Skip to content

Instantly share code, notes, and snippets.

@jacoby
Created March 27, 2014 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacoby/9813284 to your computer and use it in GitHub Desktop.
Save jacoby/9813284 to your computer and use it in GitHub Desktop.
Test of the Perl module Promise, pulled from https://github.com/stevan/promises-perl
#!/home/jacoby/perl-5.18.0/bin/perl
use feature qw'say' ;
use strict ;
use warnings ;
use utf8 ;
use AnyEvent::HTTP;
use JSON::XS qw[ decode_json ];
use Promises qw[ collect deferred ];
sub fetch_it {
my ($uri) = @_;
my $d = deferred;
http_get $uri => sub {
my ($body, $headers) = @_;
$headers->{Status} == 200
? $d->resolve( decode_json( $body ) )
: $d->reject( $body )
};
$d->promise;
}
my $cv = AnyEvent->condvar;
collect(
fetch_it('http://rest.api.example.com/-/product/12345'),
fetch_it('http://rest.api.example.com/-/product/suggestions?for_sku=12345'),
fetch_it('http://rest.api.example.com/-/product/reviews?for_sku=12345'),
)->then(
sub {
my ($product, $suggestions, $reviews) = @_;
$cv->send({
product => $product,
suggestions => $suggestions,
reviews => $reviews,
})
},
sub { $cv->croak( 'ERROR' ) }
);
my $all_product_info = $cv->recv;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment