1Promises::Cookbook::ChaUisneirngCAonndtPriipbeuPltrieondmiinPsgee(rs3l:):DCoocoukmbeonotka:t:iCohnainingAndPipelining(3)
2
3
4
6 Promises::Cookbook::ChainingAndPipelining - Examples of
7 chaining/pipelining of asynchronous operations
8
10 version 1.04
11
13 my $cv = AnyEvent->condvar;
14
15 fetch_it(
16 'http://rest.api.example.com/-/user/search?access_level=admin'
17 )->then(
18 sub {
19 my $admins = shift;
20 collect(
21 map {
22 fetch_it( 'http://rest.api.example.com/-/user/' . url_encode( $_->{user_id} ) )
23 } @$admins
24 );
25 }
26 )->then(
27 sub { $cv->send( @_ ) },
28 sub { $cv->croak( 'ERROR' ) }
29 );
30
31 my @all_admins = $cv->recv;
32
34 So one of the real benefits of the Promise pattern is how it allows you
35 to write code that flows and reads more like synchronous code by using
36 the chaining nature of Promises. In example above we are first fetching
37 a list of users whose access level is 'admin', in our fictional web-
38 service we get back a list of JSON objects with only minimal
39 information, just a user_id and full_name for instance. From here we
40 can then loop through the results and fetch the full user object for
41 each one of these users, passing all of the promises returned by
42 "fetch_it" into "collect", which itself returns a promise.
43
44 So despite being completely asynchronous, this code reads much like a
45 blocking synchronous version would read, from top to bottom.
46
47 my @all_admins;
48 try {
49 my $admins = fetch_it( 'http://rest.api.example.com/-/user/search?access_level=admin' );
50 @all_admins = map {
51 fetch_it( 'http://rest.api.example.com/-/user/' . url_encode( $_->{user_id} ) )
52 } @$admins;
53 } catch {
54 die $_;
55 };
56 # do something with @all_admins ...
57
58 The only difference really are the "then" wrappers and the way in which
59 we handle errors, but even that is very similar since we are not
60 including an error callback in the first "then" and allowing the errors
61 to bubble till the final "then", which maps very closely to the
62 "try/catch" block. And of course the Promise version runs
63 asynchronously and reaps all the benefits that brings.
64
66 Stevan Little <stevan.little@iinteractive.com>
67
69 This software is copyright (c) 2020, 2019, 2017, 2014, 2012 by Infinity
70 Interactive, Inc.
71
72 This is free software; you can redistribute it and/or modify it under
73 the same terms as the Perl 5 programming language system itself.
74
75
76
77perl v5.34.0 2P0r2o2m-i0s1e-s2:1:Cookbook::ChainingAndPipelining(3)