Skip to content

Instantly share code, notes, and snippets.

@xsawyerx
Last active December 14, 2015 21:39
Show Gist options
  • Save xsawyerx/5152738 to your computer and use it in GitHub Desktop.
Save xsawyerx/5152738 to your computer and use it in GitHub Desktop.
Recursive deferred promises: sometimes you need to run a set of actions consecutively without knowing how many actions exist. An example would be running an arbitrary number of commands one after the other. You want to be able to add more commands to the array without having to add another explicit deferred promise. This code shows how to recurs…
use strict;
use warnings;
use AnyEvent;
use AnyEvent::HTTP;
use Promises 'deferred';
my @urls = ( 'https://ddg.gg', 'http://dyndns.org', 'http://metacpan.org' );
my $cv = AE::cv;
my $cb; $cb = sub {
my $url = shift @urls or return $cv->send;
my $def = deferred;
http_get $url, sub { $def->resolve };
$def->promise->then($cb);
};
# first call
my $def = deferred;
http_get shift(@urls), sub { $def->resolve };
$def->promise->then($cb);
$cv->recv;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment