Future-Mojo

 view release on metacpan or  search on metacpan

lib/Future/Mojo.pm  view on Meta::CPAN

package Future::Mojo;

use strict;
use warnings;
use Carp 'croak';
use Scalar::Util 'blessed', 'weaken';
use Mojo::IOLoop;
use Role::Tiny::With;

use parent 'Future';

our $VERSION = '1.003';

with 'Future::Role::Promisify';

sub new {

lib/Future/Mojo.pm  view on Meta::CPAN

		? $proto->new(shift) : $proto->new;
	
	$self->_set_timer(0, @_);
	
	return $self;
}

sub _set_timer {
	my ($self, $succeed, $after) = @_;
	
	weaken(my $weakself = $self);
	my $cb = $succeed ? sub { $weakself->done if $weakself }
		: sub { $weakself->fail('Timeout') if $weakself };
	my $id = $self->loop->timer($after => $cb);
	
	$self->on_cancel(sub { shift->loop->remove($id) });
	
	return $self;
}

sub loop { shift->udata('loop') }

sub await {
	my $self = shift;
	croak 'Awaiting a future while the event loop is running would recurse'
		if $self->loop->is_running;
	$self->loop->one_tick until $self->is_ready;
}

sub done_next_tick {
	weaken(my $self = shift);
	my @result = @_;
	
	$self->loop->next_tick(sub { $self->done(@result) if $self });
	
	return $self;
}

sub fail_next_tick {
	weaken(my $self = shift);
	my ($exception, @details) = @_;
	
	croak 'Expected a true exception' unless $exception;
	
	$self->loop->next_tick(sub { $self->fail($exception, @details) if $self });
	
	return $self;
}

1;



( run in 0.770 second using v1.01-cache-2.11-cpan-65fba6d93b7 )