Acme-Sort-Sleep
view release on metacpan or search on metacpan
local/lib/perl5/Future/Phrasebook.pod view on Meta::CPAN
# You may distribute under the terms of either the GNU General Public License
# or the Artistic License (the same terms as Perl itself)
#
# (C) Paul Evans, 2013-2014 -- leonerd@leonerd.org.uk
=head1 NAME
C<Future::Phrasebook> - coding examples for C<Future> and C<Future::Utils>
This documentation-only module provides a phrasebook-like approach to giving
examples on how to use L<Future> and L<Future::Utils> to structure
Future-driven asynchronous or concurrent logic. As with any inter-dialect
phrasebook it is structured into pairs of examples; each given first in a
traditional call/return Perl style, and second in a style using Futures. In
each case, the generic function or functions in the example are named in
C<ALL_CAPITALS()> to make them stand out.
In the examples showing use of Futures, any function that is expected to
return a C<Future> instance is named with a leading C<F_> prefix. Each example
is also constructed so as to yield an overall future in a variable called
C<$f>, which represents the entire operation.
=head1 SEQUENCING
The simplest example of a sequencing operation is simply running one piece of
code, then immediately running a second. In call/return code we can just place
one after the other.
FIRST();
SECOND();
Using a Future it is necessary to await the result of the first C<Future>
before calling the second.
my $f = F_FIRST()
->then( sub { F_SECOND(); } );
Here, the anonymous closure is invoked once the C<Future> returned by
C<F_FIRST()> succeeds. Because C<then> invokes the code block only if the
first Future succeeds, it shortcircuits around failures similar to the way that
C<die()> shortcircuits around thrown exceptions. A C<Future> representing the
entire combination is returned by the method.
Because the C<then> method itself returns a C<Future> representing the
overall operation, it can itself be further chained.
FIRST();
SECOND();
THIRD();
Z<>
my $f = F_FIRST()
->then( sub { F_SECOND(); } )
->then( sub { F_THIRD(); } );
See below for examples of ways to handle exceptions.
=head2 Passing Results
Often the result of one function can be passed as an argument to another
function.
OUTER( INNER() );
The result of the first C<Future> is passed into the code block given to the
C<then> method.
my $f = F_INNER()
->then( sub { F_OUTER( @_ ) } );
=head1 CONDITIONALS
( run in 0.928 second using v1.01-cache-2.11-cpan-8f98c5d2c55 )