Skip to content

Instantly share code, notes, and snippets.

@marcoarthur
Created January 16, 2024 01:48
Show Gist options
  • Save marcoarthur/5535c0605411e54d36dc646eac07545c to your computer and use it in GitHub Desktop.
Save marcoarthur/5535c0605411e54d36dc646eac07545c to your computer and use it in GitHub Desktop.
Using map to create 3 async timers.
use v5.28;
use Mojo::Base -strict, -async_await, -signatures;
use Mojo::Promise;
=pod
=head2 myTimer($time, sub { ... });
myTimer(3 => sub { say "printed 3 seconds later" });
=cut
async sub myTimer ($time, $run) {
my $p = Mojo::Promise->new;
$p->tap(
sub {
$_->ioloop->timer($time => sub { $p->resolve( $run->() ); });
}
);
}
=pod
=head2 $promise->map()
Using map to create 3 async timers.
=cut
my @times = 1..3;
Mojo::Promise->map(
{ concurrency => scalar(@times) },
sub ($nth) {
my $time = int(rand(2**($nth)));
myTimer(
$time,
sub { say "I am the ${nth}-th promise, resolved after $time secs" }
);
},
@times
)->finally(
sub{ my $n = @times; say "all ($n) promises resolved" }
)
->wait;
exit 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment