Mojo::Promise(3pm) | User Contributed Perl Documentation | Mojo::Promise(3pm) |
Mojo::Promise - Promises/A+
use Mojo::Promise; use Mojo::UserAgent; # Wrap continuation-passing style APIs with promises my $ua = Mojo::UserAgent->new; sub get_p { my $promise = Mojo::Promise->new; $ua->get(@_ => sub ($ua, $tx) { my $err = $tx->error; if (!$err || $err->{code}) { $promise->resolve($tx) } else { $promise->reject($err->{message}) } }); return $promise; } # Perform non-blocking operations sequentially get_p('https://mojolicious.org')->then(sub ($mojo) { say $mojo->res->code; return get_p('https://metacpan.org'); })->then(sub ($cpan) { say $cpan->res->code; })->catch(sub ($err) { warn "Something went wrong: $err"; })->wait; # Synchronize non-blocking operations (all) my $mojo = get_p('https://mojolicious.org'); my $cpan = get_p('https://metacpan.org'); Mojo::Promise->all($mojo, $cpan)->then(sub ($mojo, $cpan) { say $mojo->[0]->res->code; say $cpan->[0]->res->code; })->catch(sub ($err) { warn "Something went wrong: $err"; })->wait; # Synchronize non-blocking operations (race) my $mojo = get_p('https://mojolicious.org'); my $cpan = get_p('https://metacpan.org'); Mojo::Promise->race($mojo, $cpan)->then(sub ($tx) { say $tx->req->url, ' won!'; })->catch(sub ($err) { warn "Something went wrong: $err"; })->wait;
Mojo::Promise is a Perl-ish implementation of Promises/A+ <https://promisesaplus.com> and a superset of ES6 Promises <https://duckduckgo.com/?q=n%20Promise>.
A promise is an object representing the eventual completion or failure of a non-blocking operation. It allows non-blocking functions to return values, like blocking functions. But instead of immediately returning the final value, the non-blocking function returns a promise to supply the value at some point in the future.
A promise can be in one of three states:
A pending promise can either be fulfilled with a value or rejected with a reason. When either happens, the associated handlers queued up by a promise's "then" method are called.
Mojo::Promise implements the following attributes.
my $loop = $promise->ioloop; $promise = $promise->ioloop(Mojo::IOLoop->new);
Event loop object to control, defaults to the global Mojo::IOLoop singleton. Note that this attribute is weakened.
Mojo::Promise inherits all methods from Mojo::Base and implements the following new ones.
my $new = Mojo::Promise->all(@promises);
Returns a new Mojo::Promise object that either fulfills when all of the passed Mojo::Promise objects have fulfilled or rejects as soon as one of them rejects. If the returned promise fulfills, it is fulfilled with the values from the fulfilled promises in the same order as the passed promises.
my $new = Mojo::Promise->all_settled(@promises);
Returns a new Mojo::Promise object that fulfills when all of the passed Mojo::Promise objects have fulfilled or rejected, with hash references that describe the outcome of each promise.
my $new = Mojo::Promise->any(@promises);
Returns a new Mojo::Promise object that fulfills as soon as one of the passed Mojo::Promise objects fulfills, with the value from that promise.
my $new = $promise->catch(sub {...});
Appends a rejection handler callback to the promise, and returns a new Mojo::Promise object resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled.
# Longer version my $new = $promise->then(undef, sub {...}); # Pass along the rejection reason $promise->catch(sub (@reason) { warn "Something went wrong: $reason[0]"; return @reason; }); # Change the rejection reason $promise->catch(sub (@reason) { "This is bad: $reason[0]" });
my $new = $promise->clone;
Return a new Mojo::Promise object cloned from this promise that is still pending.
my $new = $promise->finally(sub {...});
Appends a fulfillment and rejection handler to the promise, and returns a new Mojo::Promise object resolving to the original fulfillment value or rejection reason.
# Do something on fulfillment and rejection $promise->finally(sub { say "We are done!" });
my $new = Mojo::Promise->map(sub {...}, @items); my $new = Mojo::Promise->map({concurrency => 3}, sub {...}, @items);
Apply a function that returns a Mojo::Promise to each item in a list of items while optionally limiting concurrency. Returns a Mojo::Promise that collects the results in the same manner as "all". If any item's promise is rejected, any remaining items which have not yet been mapped will not be.
# Perform 3 requests at a time concurrently Mojo::Promise->map({concurrency => 3}, sub { $ua->get_p($_) }, @urls) ->then(sub{ say $_->[0]->res->dom->at('title')->text for @_ });
These options are currently available:
concurrency => 3
The maximum number of items that are in progress at the same time.
my $promise = Mojo::Promise->new; my $promise = Mojo::Promise->new(sub {...});
Construct a new Mojo::Promise object.
# Wrap a continuation-passing style API my $promise = Mojo::Promise->new(sub ($resolve, $reject) { Mojo::IOLoop->timer(5 => sub { if (int rand 2) { $resolve->('Lucky!') } else { $reject->('Unlucky!') } }); });
my $new = Mojo::Promise->race(@promises);
Returns a new Mojo::Promise object that fulfills or rejects as soon as one of the passed Mojo::Promise objects fulfills or rejects, with the value or reason from that promise.
my $new = Mojo::Promise->reject(@reason); $promise = $promise->reject(@reason);
Build rejected Mojo::Promise object or reject the promise with one or more rejection reasons.
# Longer version my $promise = Mojo::Promise->new->reject(@reason);
my $new = Mojo::Promise->resolve(@value); $promise = $promise->resolve(@value);
Build resolved Mojo::Promise object or resolve the promise with one or more fulfillment values.
# Longer version my $promise = Mojo::Promise->new->resolve(@value);
my $new = $promise->then(sub {...}); my $new = $promise->then(sub {...}, sub {...}); my $new = $promise->then(undef, sub {...});
Appends fulfillment and rejection handlers to the promise, and returns a new Mojo::Promise object resolving to the return value of the called handler.
# Pass along the fulfillment value or rejection reason $promise->then( sub (@value) { say "The result is $value[0]"; return @value; }, sub (@reason) { warn "Something went wrong: $reason[0]"; return @reason; } ); # Change the fulfillment value or rejection reason $promise->then( sub (@value) { return "This is good: $value[0]" }, sub (@reason) { return "This is bad: $reason[0]" } );
my $new = Mojo::Promise->timer(5 => 'Success!'); $promise = $promise->timer(5 => 'Success!'); $promise = $promise->timer(5);
Create a new Mojo::Promise object with a timer or attach a timer to an existing promise. The promise will be resolved after the given amount of time in seconds with or without a value.
my $new = Mojo::Promise->timeout(5 => 'Timeout!'); $promise = $promise->timeout(5 => 'Timeout!'); $promise = $promise->timeout(5);
Create a new Mojo::Promise object with a timeout or attach a timeout to an existing promise. The promise will be rejected after the given amount of time in seconds with a reason, which defaults to "Promise timeout".
$promise->wait;
Start "ioloop" and stop it again once the promise has been fulfilled or rejected, does nothing when "ioloop" is already running.
You can set the "MOJO_PROMISE_DEBUG" environment variable to get some advanced diagnostics information printed to "STDERR".
MOJO_PROMISE_DEBUG=1
Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.
2022-12-22 | perl v5.36.0 |