Permalink
Browse files

show how to wrap a continuation-passing style API with promises

  • Loading branch information...
kraih committed Oct 24, 2017
1 parent 21d79e5 commit 16733a865f427b4b091fd70491fc9911014313ca
Showing with 24 additions and 0 deletions.
  1. +12 −0 lib/Mojo/IOLoop.pm
  2. +12 −0 lib/Mojo/IOLoop/Delay.pm
View
@@ -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) {
View
@@ -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!' });

0 comments on commit 16733a8

Please sign in to comment.