Skip to content

Commit

Permalink
show how to wrap a continuation-passing style API with promises
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Oct 24, 2017
1 parent 21d79e5 commit 16733a8
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/Mojo/IOLoop.pm
Expand Up @@ -409,6 +409,18 @@ takes the same arguments as L<Mojo::IOLoop::Client/"connect">.
Build L<Mojo::IOLoop::Delay> object to use as a promise or for flow-control.
Callbacks will be passed along to L<Mojo::IOLoop::Delay/"steps">.
# Wrap continuation-passing style API with promises
my $ua = Mojo::UserAgent->new;
sub aget {
my $promise = Mojo::IOLoop->delay;
$ua->get(@_ => sub {
my ($ua, $tx) = @_;
$promise->resolve($tx);
});
return $promise;
}
aget('http://mojolicious.org')->then(sub { say shift->res->code })->wait;
# Synchronize multiple non-blocking operations
my $delay = Mojo::IOLoop->delay(sub { say 'BOOM!' });
for my $i (1 .. 10) {
Expand Down
12 changes: 12 additions & 0 deletions lib/Mojo/IOLoop/Delay.pm
Expand Up @@ -183,6 +183,18 @@ Mojo::IOLoop::Delay - Promises/A+ and flow-control helpers
use Mojo::IOLoop::Delay;
# Wrap continuation-passing style API with promises
my $ua = Mojo::UserAgent->new;
sub aget {
my $promise = Mojo::IOLoop->delay;
$ua->get(@_ => sub {
my ($ua, $tx) = @_;
$promise->resolve($tx);
});
return $promise;
}
aget('http://mojolicious.org')->then(sub { say shift->res->code })->wait;
# Synchronize multiple non-blocking operations
my $delay = Mojo::IOLoop::Delay->new;
$delay->steps(sub { say 'BOOM!' });
Expand Down

0 comments on commit 16733a8

Please sign in to comment.