AnyEvent-Promises

 view release on metacpan or  search on metacpan

lib/AnyEvent/Promises.pm  view on Meta::CPAN

    );
        
    
    my $cv = AE::cv;
    # the condvar has to be finished somehow
    $cv->recv;

=head1 DESCRIPTION

AnyEvent::Promises is an implementation of the Promise pattern for
asynchronous programming - see L<http://promises-aplus.github.io/promises-spec/>.

Promises are the way how to structure your asynchronous code to avoid 
so called callback hell. 

=head1 METHODS

There are two classes of objects - deferred objects and promise objects. 
Both classes are "private", the objects are created by calling functions 
from L<AnyEvent::Promises>.

Typically a producer creates a deferred object, so it can resolve or reject
it asynchronously while returning the consumer part of deferred object (the
promise) synchronously to the consumer.

The consumer can synchronously "install handlers" on promise object 
to be notified when the underlying deferred object is resolved or rejected.

The deferred object is created via C<deferred> function (see EXPORTS).

The promise object is typically created via C<< $deferred->promise >>
or C<< $promise->then >>.

=head2 Methods of deferred (producers)

=over 4

lib/AnyEvent/Promises.pm  view on Meta::CPAN

=item C<sync([$timeout])>

    use AnyEvent::Promises qw(make_promise deferred);
    
    make_promise(8)->sync; # returns 8
    make_promise(sub { die "Oops" })->sync; # dies with Oops

    deferred()->promise->sync; # after 5 seconds dies with "TIMEOUT\n"
    deferred()->promise->sync(10); # after 10 seconds dies with "TIMEOUT\n"

Runs the promise synchronously. Runs new event loop which is finished
after $timeout (default 5) seconds or when the promise gets fulfilled 
or rejected.

If the promise gets fulfilled before timeout, returns the values of the promise.
If the promise gets rejected before timeout, dies with the reason of the promise.
Otherwise dies with C<TIMEOUT> string.

=item C<values>

If the promise was fulfilled, returns the values the underlying deferred object was resolved with.

lib/AnyEvent/Promises/Deferred.pm  view on Meta::CPAN

    my $d = ref($this)->new;
    if ( my $then = $this->{then} ) {
        push @$then, [ $d, @_ ];
    }
    else {
        $this->_do_then( $d, @_ );
    }
    return $d->promise;
}

# runs the promise synchronously
sub _promise_sync {
    my $this = shift;
    my $timeout = shift || 5;

    my $cv      = AE::cv;
    my $tm      = AE::timer $timeout, 0, sub { $cv->send("TIMEOUT\n") };
    $this->_promise_then( sub { $cv->send( undef, @_ ); }, sub { $cv->send(@_) } );
    my ( $error, @res ) = $cv->recv;

    die $error if $error;



( run in 0.617 second using v1.01-cache-2.11-cpan-0d8aa00de5b )