View on
MetaCPAN is shutting down
For details read Perl NOC. After June 25th this page will redirect to
Stevan Little > Promises-0.04 > Promises::Cookbook::ChainingAndPipelining


Annotate this POD


Open  5
View/Report Bugs
Source   Latest Release: Promises-0.99


Promises::Cookbook::ChainingAndPipelining - Examples of chaining/pipelining of asynchronous operations


version 0.04


  my $cv = AnyEvent->condvar;

      sub {
          my $admins = shift;
              map {
                  fetch_it( '' . url_encode( $_->{user_id} ) )
              } @$admins
      sub { $cv->send( @_ ) },
      sub { $cv->croak( 'ERROR' ) }

  my @all_admins = $cv->recv;


So one of the real benefits of the Promise pattern is how it allows you to write code that flows and reads more like synchronous code by using the chaining nature of Promises. In example above we are first fetching a list of users whose access level is 'admin', in our fictional web-service we get back a list of JSON objects with only minimal information, just a user_id and full_name for instance. From here we can then loop through the results and fetch the full user object for each one of these users, passing all of the promises returned by fetch_it into collect, which itself returns a promise.

So despite being completely asynchronous, this code reads much like a blocking synchronous version would read, from top to bottom.

  my @all_admins;
  try {
      my $admins = fetch_it( '' );
      @all_admins = map {
          fetch_it( '' . url_encode( $_->{user_id} ) )
      } @$admins;
  } catch {
      die $_;
  # do something with @all_admins ...

The only difference really are the then wrappers and the way in which we handle errors, but even that is very similar since we are not including an error callback in the first then and allowing the errors to bubble till the final then, which maps very closely to the try/catch block. And of course the Promise version runs asynchronously and reaps all the benefits that brings.


Stevan Little <>


This software is copyright (c) 2012 by Infinity Interactive, Inc..

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.

syntax highlighting: