Created
October 26, 2018 21:11
-
-
Save jberger/ff1004895343449e18a49f642742569f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use Mojo::Base -strict; | |
use Test::More; | |
use Carp (); | |
use Mojo::Promise; | |
sub await; | |
sub async { | |
my $body = shift; | |
my $wrapper = sub { | |
local *await = sub { | |
my $p = shift; | |
my (@retvals, $err); | |
$p->then(sub{ | |
@retvals = @_; | |
goto DONE; | |
}, | |
sub { | |
$err = shift; | |
goto DONE; | |
} | |
); | |
goto START; | |
DONE: { | |
Carp::croak($err) if $err; | |
return wantarray ? @retvals : $retvals[0]; | |
}; | |
}; | |
my $p = Mojo::Promise->new; | |
eval { $p->resolve($body->(@_)); 1 } or $p->reject($@); | |
START: return $p; | |
}; | |
return $wrapper; | |
} | |
sub double { | |
my $in = shift; | |
my $p = Mojo::Promise->new; | |
Mojo::IOLoop->timer(0.5 => sub { $p->resolve(2 * $in) }); | |
return $p; | |
} | |
my $tick = 0; | |
Mojo::IOLoop->recurring(0.1 => sub { $tick++ }); | |
my $answer; | |
async(sub { $answer = await double(21) })->()->wait; | |
Mojo::IOLoop->timer( | |
5 => sub { | |
fail 'timeout'; | |
Mojo::IOLoop->stop; | |
} | |
); | |
is $answer, 42, 'got expected answer'; | |
ok $tick > 2, 'got multiple ticks'; | |
done_testing; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment