GSP
Quick Navigator

Search Site

Unix VPS
A - Starter
B - Basic
C - Preferred
D - Commercial
MPS - Dedicated
Previous VPSs
* Sign Up! *

Support
Contact Us
Online Help
Handbooks
Domain Status
Man Pages

FAQ
Virtual Servers
Pricing
Billing
Technical

Network
Facilities
Connectivity
Topology Map

Miscellaneous
Server Agreement
Year 2038
Credits
 

USA Flag

 

 

Man Pages
Promises::Cookbook::ChainingAndPipelining(3) User Contributed Perl Documentation Promises::Cookbook::ChainingAndPipelining(3)

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

version 0.94

  my $cv = AnyEvent->condvar;

  fetch_it(
      'http://rest.api.example.com/-/user/search?access_level=admin'
  )->then(
      sub {
          my $admins = shift;
          collect(
              map {
                  fetch_it( 'http://rest.api.example.com/-/user/' . url_encode( $_->{user_id} ) )
              } @$admins
          );
      }
  )->then(
      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( 'http://rest.api.example.com/-/user/search?access_level=admin' );
      @all_admins = map {
          fetch_it( 'http://rest.api.example.com/-/user/' . 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 <stevan.little@iinteractive.com>

This software is copyright (c) 2014 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.

2014-12-28 perl v5.32.1

Search for    or go to Top of page |  Section 3 |  Main Index

Powered by GSP Visit the GSP FreeBSD Man Page Interface.
Output converted with ManDoc.