1Future(3)             User Contributed Perl Documentation            Future(3)
2
3
4

NAME

6       "Future" - represent an operation awaiting completion
7

SYNOPSIS

9        my $future = Future->new;
10
11        perform_some_operation(
12           on_complete => sub {
13              $future->done( @_ );
14           }
15        );
16
17        $future->on_ready( sub {
18           say "The operation is complete";
19        } );
20

DESCRIPTION

22       A "Future" object represents an operation that is currently in
23       progress, or has recently completed. It can be used in a variety of
24       ways to manage the flow of control, and data, through an asynchronous
25       program.
26
27       Some futures represent a single operation and are explicitly marked as
28       ready by calling the "done" or "fail" methods. These are called "leaf"
29       futures here, and are returned by the "new" constructor.
30
31       Other futures represent a collection of sub-tasks, and are implicitly
32       marked as ready depending on the readiness of their component futures
33       as required.  These are called "convergent" futures here as they
34       converge control and data-flow back into one place. These are the ones
35       returned by the various "wait_*" and "need_*" constructors.
36
37       It is intended that library functions that perform asynchronous
38       operations would use future objects to represent outstanding
39       operations, and allow their calling programs to control or wait for
40       these operations to complete. The implementation and the user of such
41       an interface would typically make use of different methods on the
42       class. The methods below are documented in two sections; those of
43       interest to each side of the interface.
44
45       It should be noted however, that this module does not in any way
46       provide an actual mechanism for performing this asynchronous activity;
47       it merely provides a way to create objects that can be used for control
48       and data flow around those operations. It allows such code to be
49       written in a neater, forward-reading manner, and simplifies many common
50       patterns that are often involved in such situations.
51
52       See also Future::Utils which contains useful loop-constructing
53       functions, to run a future-returning function repeatedly in a loop.
54
55       Unless otherwise noted, the following methods require at least version
56       0.08.
57
58   FAILURE CATEGORIES
59       While not directly required by "Future" or its related modules, a
60       growing convention of "Future"-using code is to encode extra semantics
61       in the arguments given to the "fail" method, to represent different
62       kinds of failure.
63
64       The convention is that after the initial message string as the first
65       required argument (intended for display to humans), the second argument
66       is a short lowercase string that relates in some way to the kind of
67       failure that occurred. Following this is a list of details about that
68       kind of failure, whose exact arrangement or structure are determined by
69       the failure category.  For example, IO::Async and Net::Async::HTTP use
70       this convention to indicate at what stage a given HTTP request has
71       failed:
72
73          ->fail( $message, http => ... )  # an HTTP-level error during protocol
74          ->fail( $message, connect => ... )  # a TCP-level failure to connect a
75                                              # socket
76          ->fail( $message, resolve => ... )  # a resolver (likely DNS) failure
77                                              # to resolve a hostname
78
79       By following this convention, a module remains consistent with other
80       "Future"-based modules, and makes it easy for program logic to
81       gracefully handle and manage failures by use of the "catch" method.
82
83   SUBCLASSING
84       This class easily supports being subclassed to provide extra behavior,
85       such as giving the "get" method the ability to block and wait for
86       completion. This may be useful to provide "Future" subclasses with
87       event systems, or similar.
88
89       Each method that returns a new future object will use the invocant to
90       construct its return value. If the constructor needs to perform per-
91       instance setup it can override the "new" method, and take context from
92       the given instance.
93
94        sub new
95        {
96           my $proto = shift;
97           my $self = $proto->SUPER::new;
98
99           if( ref $proto ) {
100              # Prototype was an instance
101           }
102           else {
103              # Prototype was a class
104           }
105
106           return $self;
107        }
108
109       If an instance provides a method called "await", this will be called by
110       the "get" and "failure" methods if the instance is pending.
111
112        $f->await
113
114       In most cases this should allow future-returning modules to be used as
115       if they were blocking call/return-style modules, by simply appending a
116       "get" call to the function or method calls.
117
118        my ( $results, $here ) = future_returning_function( @args )->get;
119
120       The examples directory in the distribution contains some examples of
121       how futures might be integrated with various event systems.
122
123   DEBUGGING
124       By the time a "Future" object is destroyed, it ought to have been
125       completed or cancelled. By enabling debug tracing of objects, this fact
126       can be checked.  If a future object is destroyed without having been
127       completed or cancelled, a warning message is printed.
128
129        $ PERL_FUTURE_DEBUG=1 perl -MFuture -E 'my $f = Future->new'
130        Future=HASH(0xaa61f8) was constructed at -e line 1 and was lost near -e line 0 before it was ready.
131
132       Note that due to a limitation of perl's "caller" function within a
133       "DESTROY" destructor method, the exact location of the leak cannot be
134       accurately determined. Often the leak will occur due to falling out of
135       scope by returning from a function; in this case the leak location may
136       be reported as being the line following the line calling that function.
137
138        $ PERL_FUTURE_DEBUG=1 perl -MFuture
139        sub foo {
140           my $f = Future->new;
141        }
142
143        foo();
144        print "Finished\n";
145
146        Future=HASH(0x14a2220) was constructed at - line 2 and was lost near - line 6 before it was ready.
147        Finished
148
149       A warning is also printed in debug mode if a "Future" object is
150       destroyed that completed with a failure, but the object believes that
151       failure has not been reported anywhere.
152
153        $ PERL_FUTURE_DEBUG=1 perl -Mblib -MFuture -E 'my $f = Future->fail("Oops")'
154        Future=HASH(0xac98f8) was constructed at -e line 1 and was lost near -e line 0 with an unreported failure of: Oops
155
156       Such a failure is considered reported if the "get" or "failure" methods
157       are called on it, or it had at least one "on_ready" or "on_fail"
158       callback, or its failure is propagated to another "Future" instance (by
159       a sequencing or converging method).
160

CONSTRUCTORS

162   new
163          $future = Future->new
164
165          $future = $orig->new
166
167       Returns a new "Future" instance to represent a leaf future. It will be
168       marked as ready by any of the "done", "fail", or "cancel" methods. It
169       can be called either as a class method, or as an instance method.
170       Called on an instance it will construct another in the same class, and
171       is useful for subclassing.
172
173       This constructor would primarily be used by implementations of
174       asynchronous interfaces.
175
176   done (class method)
177   fail (class method)
178          $future = Future->done( @values )
179
180          $future = Future->fail( $exception, @details )
181
182       Since version 0.26.
183
184       Shortcut wrappers around creating a new "Future" then immediately
185       marking it as done or failed.
186
187   wrap
188          $future = Future->wrap( @values )
189
190       Since version 0.14.
191
192       If given a single argument which is already a "Future" reference, this
193       will be returned unmodified. Otherwise, returns a new "Future" instance
194       that is already complete, and will yield the given values.
195
196       This will ensure that an incoming argument is definitely a "Future",
197       and may be useful in such cases as adapting synchronous code to fit
198       asynchronous libraries driven by "Future".
199
200   call
201          $future = Future->call( \&code, @args )
202
203       Since version 0.15.
204
205       A convenient wrapper for calling a "CODE" reference that is expected to
206       return a future. In normal circumstances is equivalent to
207
208        $future = $code->( @args )
209
210       except that if the code throws an exception, it is wrapped in a new
211       immediate fail future. If the return value from the code is not a
212       blessed "Future" reference, an immediate fail future is returned
213       instead to complain about this fact.
214

METHODS

216       As there are a lare number of methods on this class, they are
217       documented here in several sections.
218

INSPECTION METHODS

220       The following methods query the internal state of a Future instance
221       without modifying it or otherwise causing side-effects.
222
223   is_ready
224          $ready = $future->is_ready
225
226       Returns true on a leaf future if a result has been provided to the
227       "done" method, failed using the "fail" method, or cancelled using the
228       "cancel" method.
229
230       Returns true on a convergent future if it is ready to yield a result,
231       depending on its component futures.
232
233   is_done
234          $done = $future->is_done
235
236       Returns true on a future if it is ready and completed successfully.
237       Returns false if it is still pending, failed, or was cancelled.
238
239   is_failed
240          $failed = $future->is_failed
241
242       Since version 0.26.
243
244       Returns true on a future if it is ready and it failed. Returns false if
245       it is still pending, completed successfully, or was cancelled.
246
247   is_cancelled
248          $cancelled = $future->is_cancelled
249
250       Returns true if the future has been cancelled by "cancel".
251
252   state
253          $str = $future->state
254
255       Since version 0.36.
256
257       Returns a string describing the state of the future, as one of the
258       three states named above; namely "done", "failed" or "cancelled", or
259       "pending" if it is none of these.
260

IMPLEMENTATION METHODS

262       These methods would primarily be used by implementations of
263       asynchronous interfaces.
264
265   done
266          $future->done( @result )
267
268       Marks that the leaf future is now ready, and provides a list of values
269       as a result. (The empty list is allowed, and still indicates the future
270       as ready).  Cannot be called on a convergent future.
271
272       If the future is already cancelled, this request is ignored. If the
273       future is already complete with a result or a failure, an exception is
274       thrown.
275
276   fail
277          $future->fail( $exception, @details )
278
279       Marks that the leaf future has failed, and provides an exception value.
280       This exception will be thrown by the "get" method if called.
281
282       The exception must evaluate as a true value; false exceptions are not
283       allowed.  Further details may be provided that will be returned by the
284       "failure" method in list context. These details will not be part of the
285       exception string raised by "get".
286
287       If the future is already cancelled, this request is ignored. If the
288       future is already complete with a result or a failure, an exception is
289       thrown.
290
291   die
292          $future->die( $message, @details )
293
294       Since version 0.09.
295
296       A convenient wrapper around "fail". If the exception is a non-reference
297       that does not end in a linefeed, its value will be extended by the file
298       and line number of the caller, similar to the logic that "die" uses.
299
300       Returns the $future.
301
302   on_cancel
303          $future->on_cancel( $code )
304
305       If the future is not yet ready, adds a callback to be invoked if the
306       future is cancelled by the "cancel" method. If the future is already
307       ready, throws an exception.
308
309       If the future is cancelled, the callbacks will be invoked in the
310       reverse order to that in which they were registered.
311
312        $on_cancel->( $future )
313
314       If passed another "Future" instance, the passed instance will be
315       cancelled when the original future is cancelled. This method does
316       nothing if the future is already complete.
317

USER METHODS

319       These methods would primarily be used by users of asynchronous
320       interfaces, on objects returned by such an interface.
321
322   on_ready
323          $future->on_ready( $code )
324
325       If the future is not yet ready, adds a callback to be invoked when the
326       future is ready. If the future is already ready, invokes it
327       immediately.
328
329       In either case, the callback will be passed the future object itself.
330       The invoked code can then obtain the list of results by calling the
331       "get" method.
332
333        $on_ready->( $future )
334
335       If passed another "Future" instance, the passed instance will have its
336       "done", "fail" or "cancel" methods invoked when the original future
337       completes successfully, fails, or is cancelled respectively.
338
339       Returns the $future.
340
341   get
342          @result = $future->get
343
344          $result = $future->get
345
346       If the future is ready and completed successfully, returns the list of
347       results that had earlier been given to the "done" method on a leaf
348       future, or the list of component futures it was waiting for on a
349       convergent future. In scalar context it returns just the first result
350       value.
351
352       If the future is ready but failed, this method raises as an exception
353       the failure string or object that was given to the "fail" method.
354
355       If the future was cancelled an exception is thrown.
356
357       If it is not yet ready and is not of a subclass that provides an
358       "await" method an exception is thrown. If it is subclassed to provide
359       an "await" method then this is used to wait for the future to be ready,
360       before returning the result or propagating its failure exception.
361
362   unwrap
363          @values = Future->unwrap( @values )
364
365       Since version 0.26.
366
367       If given a single argument which is a "Future" reference, this method
368       will call "get" on it and return the result. Otherwise, it returns the
369       list of values directly in list context, or the first value in scalar.
370       Since it involves an implicit "await", this method can only be used on
371       immediate futures or subclasses that implement "await".
372
373       This will ensure that an outgoing argument is definitely not a
374       "Future", and may be useful in such cases as adapting synchronous code
375       to fit asynchronous libraries that return "Future" instances.
376
377   on_done
378          $future->on_done( $code )
379
380       If the future is not yet ready, adds a callback to be invoked when the
381       future is ready, if it completes successfully. If the future completed
382       successfully, invokes it immediately. If it failed or was cancelled, it
383       is not invoked at all.
384
385       The callback will be passed the result passed to the "done" method.
386
387        $on_done->( @result )
388
389       If passed another "Future" instance, the passed instance will have its
390       "done" method invoked when the original future completes successfully.
391
392       Returns the $future.
393
394   failure
395          $exception = $future->failure
396
397          $exception, @details = $future->failure
398
399       Returns the exception passed to the "fail" method, "undef" if the
400       future completed successfully via the "done" method, or raises an
401       exception if called on a future that is not yet ready.
402
403       If called in list context, will additionally yield a list of the
404       details provided to the "fail" method.
405
406       Because the exception value must be true, this can be used in a simple
407       "if" statement:
408
409        if( my $exception = $future->failure ) {
410           ...
411        }
412        else {
413           my @result = $future->get;
414           ...
415        }
416
417   on_fail
418          $future->on_fail( $code )
419
420       If the future is not yet ready, adds a callback to be invoked when the
421       future is ready, if it fails. If the future has already failed, invokes
422       it immediately. If it completed successfully or was cancelled, it is
423       not invoked at all.
424
425       The callback will be passed the exception and details passed to the
426       "fail" method.
427
428        $on_fail->( $exception, @details )
429
430       If passed another "Future" instance, the passed instance will have its
431       "fail" method invoked when the original future fails.
432
433       To invoke a "done" method on a future when another one fails, use a
434       CODE reference:
435
436        $future->on_fail( sub { $f->done( @_ ) } );
437
438       Returns the $future.
439
440   cancel
441          $future->cancel
442
443       Requests that the future be cancelled, immediately marking it as ready.
444       This will invoke all of the code blocks registered by "on_cancel", in
445       the reverse order. When called on a convergent future, all its
446       component futures are also cancelled. It is not an error to attempt to
447       cancel a future that is already complete or cancelled; it simply has no
448       effect.
449
450       Returns the $future.
451

SEQUENCING METHODS

453       The following methods all return a new future to represent the
454       combination of its invocant followed by another action given by a code
455       reference. The combined activity waits for the first future to be
456       ready, then may invoke the code depending on the success or failure of
457       the first, or may run it regardless. The returned sequence future
458       represents the entire combination of activity.
459
460       In some cases the code should return a future; in some it should return
461       an immediate result. If a future is returned, the combined future will
462       then wait for the result of this second one. If the combinined future
463       is cancelled, it will cancel either the first future or the second,
464       depending whether the first had completed. If the code block throws an
465       exception instead of returning a value, the sequence future will fail
466       with that exception as its message and no further values.
467
468       As it is always a mistake to call these sequencing methods in void
469       context and lose the reference to the returned future (because
470       exception/error handling would be silently dropped), this method warns
471       in void context.
472
473   then
474          $future = $f1->then( \&done_code )
475
476       Since version 0.13.
477
478       Returns a new sequencing "Future" that runs the code if the first
479       succeeds.  Once $f1 succeeds the code reference will be invoked and is
480       passed the list of results. It should return a future, $f2. Once $f2
481       completes the sequence future will then be marked as complete with
482       whatever result $f2 gave. If $f1 fails then the sequence future will
483       immediately fail with the same failure and the code will not be
484       invoked.
485
486        $f2 = $done_code->( @result )
487
488   else
489          $future = $f1->else( \&fail_code )
490
491       Since version 0.13.
492
493       Returns a new sequencing "Future" that runs the code if the first
494       fails. Once $f1 fails the code reference will be invoked and is passed
495       the failure and details. It should return a future, $f2. Once $f2
496       completes the sequence future will then be marked as complete with
497       whatever result $f2 gave. If $f1 succeeds then the sequence future will
498       immediately succeed with the same result and the code will not be
499       invoked.
500
501        $f2 = $fail_code->( $exception, @details )
502
503   then (2 arguments)
504          $future = $f1->then( \&done_code, \&fail_code )
505
506       The "then" method can also be passed the $fail_code block as well,
507       giving a combination of "then" and "else" behaviour.
508
509       This operation is designed to be compatible with the semantics of other
510       future systems, such as Javascript's Q or Promises/A libraries.
511
512   catch
513          $future = $f1->catch(
514             name => \&code,
515             name => \&code, ...
516          )
517
518       Since version 0.33.
519
520       Returns a new sequencing "Future" that behaves like an "else" call
521       which dispatches to a choice of several alternative handling functions
522       depending on the kind of failure that occurred. If $f1 fails with a
523       category name (i.e.  the second argument to the "fail" call) which
524       exactly matches one of the string names given, then the corresponding
525       code is invoked, being passed the same arguments as a plain "else" call
526       would take, and is expected to return a "Future" in the same way.
527
528        $f2 = $code->( $exception, $name, @other_details )
529
530       If $f1 does not fail, fails without a category name at all, or fails
531       with a category name that does not match any given to the "catch"
532       method, then the returned sequence future immediately completes with
533       the same result, and no block of code is invoked.
534
535       If passed an odd-sized list, the final argument gives a function to
536       invoke on failure if no other handler matches.
537
538          $future = $f1->catch(
539             name => \&code, ...
540             \&fail_code,
541          )
542
543       This feature is currently still a work-in-progress. It currently can
544       only cope with category names that are literal strings, which are all
545       distinct. A later version may define other kinds of match (e.g.
546       regexp), may specify some sort of ordering on the arguments, or any of
547       several other semantic extensions. For more detail on the ongoing
548       design, see <https://rt.cpan.org/Ticket/Display.html?id=103545>.
549
550   then (multiple arguments)
551          $future = $f1->then( \&done_code, @catch_list, \&fail_code )
552
553       Since version 0.33.
554
555       The "then" method can be passed an even-sized list inbetween the
556       $done_code and the $fail_code, with the same meaning as the "catch"
557       method.
558
559   transform
560          $future = $f1->transform( %args )
561
562       Returns a new sequencing "Future" that wraps the one given as $f1. With
563       no arguments this will be a trivial wrapper; $future will complete or
564       fail when $f1 does, and $f1 will be cancelled when $future is.
565
566       By passing the following named arguments, the returned $future can be
567       made to behave differently to $f1:
568
569       done => CODE
570               Provides a function to use to modify the result of a successful
571               completion.  When $f1 completes successfully, the result of its
572               "get" method is passed into this function, and whatever it
573               returns is passed to the "done" method of $future
574
575       fail => CODE
576               Provides a function to use to modify the result of a failure.
577               When $f1 fails, the result of its "failure" method is passed
578               into this function, and whatever it returns is passed to the
579               "fail" method of $future.
580
581   then_with_f
582          $future = $f1->then_with_f( ... )
583
584       Since version 0.21.
585
586       Returns a new sequencing "Future" that behaves like "then", but also
587       passes the original future, $f1, to any functions it invokes.
588
589        $f2 = $done_code->( $f1, @result )
590        $f2 = $catch_code->( $f1, $name, @other_details )
591        $f2 = $fail_code->( $f1, @details )
592
593       This is useful for conditional execution cases where the code block may
594       just return the same result of the original future. In this case it is
595       more efficient to return the original future itself.
596
597   then_done
598   then_fail
599          $future = $f->then_done( @result )
600
601          $future = $f->then_fail( $exception, @details )
602
603       Since version 0.22.
604
605       Convenient shortcuts to returning an immediate future from a "then"
606       block, when the result is already known.
607
608   else_with_f
609          $future = $f1->else_with_f( \&code )
610
611       Since version 0.21.
612
613       Returns a new sequencing "Future" that runs the code if the first
614       fails.  Identical to "else", except that the code reference will be
615       passed both the original future, $f1, and its exception and details.
616
617        $f2 = $code->( $f1, $exception, @details )
618
619       This is useful for conditional execution cases where the code block may
620       just return the same result of the original future. In this case it is
621       more efficient to return the original future itself.
622
623   else_done
624   else_fail
625          $future = $f->else_done( @result )
626
627          $future = $f->else_fail( $exception, @details )
628
629       Since version 0.22.
630
631       Convenient shortcuts to returning an immediate future from a "else"
632       block, when the result is already known.
633
634   catch_with_f
635          $future = $f1->catch_with_f( ... )
636
637       Since version 0.33.
638
639       Returns a new sequencing "Future" that behaves like "catch", but also
640       passes the original future, $f1, to any functions it invokes.
641
642   followed_by
643          $future = $f1->followed_by( \&code )
644
645       Returns a new sequencing "Future" that runs the code regardless of
646       success or failure. Once $f1 is ready the code reference will be
647       invoked and is passed one argument, $f1. It should return a future,
648       $f2. Once $f2 completes the sequence future will then be marked as
649       complete with whatever result $f2 gave.
650
651        $f2 = $code->( $f1 )
652
653   without_cancel
654          $future = $f1->without_cancel
655
656       Since version 0.30.
657
658       Returns a new sequencing "Future" that will complete with the success
659       or failure of the original future, but if cancelled, will not cancel
660       the original. This may be useful if the original future represents an
661       operation that is being shared among multiple sequences; cancelling one
662       should not prevent the others from running too.
663
664   retain
665          $f = $f->retain
666
667       Since version 0.36.
668
669       Creates a reference cycle which causes the future to remain in memory
670       until it completes. Returns the invocant future.
671
672       In normal situations, a "Future" instance does not strongly hold a
673       reference to other futures that it is feeding a result into, instead
674       relying on that to be handled by application logic. This is normally
675       fine because some part of the application will retain the top-level
676       Future, which then strongly refers to each of its components down in a
677       tree. However, certain design patterns, such as mixed Future-based and
678       legacy callback-based API styles might end up creating Futures simply
679       to attach callback functions to them. In that situation, without
680       further attention, the Future may get lost due to having no strong
681       references to it. Calling "->retain" on it creates such a reference
682       which ensures it persists until it completes. For example:
683
684          Future->needs_all( $fA, $fB )
685             ->on_done( $on_done )
686             ->on_fail( $on_fail )
687             ->retain;
688

CONVERGENT FUTURES

690       The following constructors all take a list of component futures, and
691       return a new future whose readiness somehow depends on the readiness of
692       those components. The first derived class component future will be used
693       as the prototype for constructing the return value, so it respects
694       subclassing correctly, or failing that a plain "Future".
695
696   wait_all
697          $future = Future->wait_all( @subfutures )
698
699       Returns a new "Future" instance that will indicate it is ready once all
700       of the sub future objects given to it indicate that they are ready,
701       either by success, failure or cancellation. Its result will be a list
702       of its component futures.
703
704       When given an empty list this constructor returns a new immediately-
705       done future.
706
707       This constructor would primarily be used by users of asynchronous
708       interfaces.
709
710   wait_any
711          $future = Future->wait_any( @subfutures )
712
713       Returns a new "Future" instance that will indicate it is ready once any
714       of the sub future objects given to it indicate that they are ready,
715       either by success or failure. Any remaining component futures that are
716       not yet ready will be cancelled. Its result will be the result of the
717       first component future that was ready; either success or failure. Any
718       component futures that are cancelled are ignored, apart from the final
719       component left; at which point the result will be a failure.
720
721       When given an empty list this constructor returns an immediately-failed
722       future.
723
724       This constructor would primarily be used by users of asynchronous
725       interfaces.
726
727   needs_all
728          $future = Future->needs_all( @subfutures )
729
730       Returns a new "Future" instance that will indicate it is ready once all
731       of the sub future objects given to it indicate that they have completed
732       successfully, or when any of them indicates that they have failed. If
733       any sub future fails, then this will fail immediately, and the
734       remaining subs not yet ready will be cancelled. Any component futures
735       that are cancelled will cause an immediate failure of the result.
736
737       If successful, its result will be a concatenated list of the results of
738       all its component futures, in corresponding order. If it fails, its
739       failure will be that of the first component future that failed. To
740       access each component future's results individually, use
741       "done_futures".
742
743       When given an empty list this constructor returns a new immediately-
744       done future.
745
746       This constructor would primarily be used by users of asynchronous
747       interfaces.
748
749   needs_any
750          $future = Future->needs_any( @subfutures )
751
752       Returns a new "Future" instance that will indicate it is ready once any
753       of the sub future objects given to it indicate that they have completed
754       successfully, or when all of them indicate that they have failed. If
755       any sub future succeeds, then this will succeed immediately, and the
756       remaining subs not yet ready will be cancelled. Any component futures
757       that are cancelled are ignored, apart from the final component left; at
758       which point the result will be a failure.
759
760       If successful, its result will be that of the first component future
761       that succeeded. If it fails, its failure will be that of the last
762       component future to fail. To access the other failures, use
763       "failed_futures".
764
765       Normally when this future completes successfully, only one of its
766       component futures will be done. If it is constructed with multiple that
767       are already done however, then all of these will be returned from
768       "done_futures". Users should be careful to still check all the results
769       from "done_futures" in that case.
770
771       When given an empty list this constructor returns an immediately-failed
772       future.
773
774       This constructor would primarily be used by users of asynchronous
775       interfaces.
776

METHODS ON CONVERGENT FUTURES

778       The following methods apply to convergent (i.e. non-leaf) futures, to
779       access the component futures stored by it.
780
781   pending_futures
782          @f = $future->pending_futures
783
784   ready_futures
785          @f = $future->ready_futures
786
787   done_futures
788          @f = $future->done_futures
789
790   failed_futures
791          @f = $future->failed_futures
792
793   cancelled_futures
794          @f = $future->cancelled_futures
795
796       Return a list of all the pending, ready, done, failed, or cancelled
797       component futures. In scalar context, each will yield the number of
798       such component futures.
799

TRACING METHODS

801   set_label
802   label
803          $future = $future->set_label( $label )
804
805          $label = $future->label
806
807       Since version 0.28.
808
809       Chaining mutator and accessor for the label of the "Future". This
810       should be a plain string value, whose value will be stored by the
811       future instance for use in debugging messages or other tooling, or
812       similar purposes.
813
814   btime
815   rtime
816          [ $sec, $usec ] = $future->btime
817
818          [ $sec, $usec ] = $future->rtime
819
820       Since version 0.28.
821
822       Accessors that return the tracing timestamps from the instance. These
823       give the time the instance was constructed ("birth" time, "btime") and
824       the time the result was determined (the "ready" time, "rtime"). Each
825       result is returned as a two-element ARRAY ref, containing the epoch
826       time in seconds and microseconds, as given by
827       "Time::HiRes::gettimeofday".
828
829       In order for these times to be captured, they have to be enabled by
830       setting $Future::TIMES to a true value. This is initialised true at the
831       time the module is loaded if either "PERL_FUTURE_DEBUG" or
832       "PERL_FUTURE_TIMES" are set in the environment.
833
834   elapsed
835          $sec = $future->elapsed
836
837       Since version 0.28.
838
839       If both tracing timestamps are defined, returns the number of seconds
840       of elapsed time between them as a floating-point number. If not,
841       returns "undef".
842
843   wrap_cb
844          $cb = $future->wrap_cb( $operation_name, $cb )
845
846       Since version 0.31.
847
848       Note: This method is experimental and may be changed or removed in a
849       later version.
850
851       This method is invoked internally by various methods that are about to
852       save a callback CODE reference supplied by the user, to be invoked
853       later. The default implementation simply returns the callback argument
854       as-is; the method is provided to allow users to provide extra
855       behaviour. This can be done by applying a method modifier of the
856       "around" kind, so in effect add a chain of wrappers. Each wrapper can
857       then perform its own wrapping logic of the callback. $operation_name is
858       a string giving the reason for which the callback is being saved;
859       currently one of "on_ready", "on_done", "on_fail" or "sequence"; the
860       latter being used for all the sequence-returning methods.
861
862       This method is intentionally invoked only for CODE references that are
863       being saved on a pending "Future" instance to be invoked at some later
864       point. It does not run for callbacks to be invoked on an already-
865       complete instance. This is for performance reasons, where the intended
866       behaviour is that the wrapper can provide some amount of context save
867       and restore, to return the operating environment for the callback back
868       to what it was at the time it was saved.
869
870       For example, the following wrapper saves the value of a package
871       variable at the time the callback was saved, and restores that value at
872       invocation time later on. This could be useful for preserving context
873       during logging in a Future-based program.
874
875        our $LOGGING_CTX;
876
877        no warnings 'redefine';
878
879        my $orig = Future->can( "wrap_cb" );
880        *Future::wrap_cb = sub {
881           my $cb = $orig->( @_ );
882
883           my $saved_logging_ctx = $LOGGING_CTX;
884
885           return sub {
886              local $LOGGING_CTX = $saved_logging_ctx;
887              $cb->( @_ );
888           };
889        };
890
891       At this point, any code deferred into a "Future" by any of its
892       callbacks will observe the $LOGGING_CTX variable as having the value it
893       held at the time the callback was saved, even if it is invoked later on
894       when that value is different.
895
896       Remember when writing such a wrapper, that it still needs to invoke the
897       previous version of the method, so that it plays nicely in combination
898       with others (see the "$orig->( @_ )" part).
899

EXAMPLES

901       The following examples all demonstrate possible uses of a "Future"
902       object to provide a fictional asynchronous API.
903
904       For more examples, comparing the use of "Future" with regular
905       call/return style Perl code, see also Future::Phrasebook.
906
907   Providing Results
908       By returning a new "Future" object each time the asynchronous function
909       is called, it provides a placeholder for its eventual result, and a way
910       to indicate when it is complete.
911
912        sub foperation
913        {
914           my %args = @_;
915
916           my $future = Future->new;
917
918           do_something_async(
919              foo => $args{foo},
920              on_done => sub { $future->done( @_ ); },
921           );
922
923           return $future;
924        }
925
926       In most cases, the "done" method will simply be invoked with the entire
927       result list as its arguments. In that case, it is convenient to use the
928       curry module to form a "CODE" reference that would invoke the "done"
929       method.
930
931           my $future = Future->new;
932
933           do_something_async(
934              foo => $args{foo},
935              on_done => $future->curry::done,
936           );
937
938       The caller may then use this future to wait for a result using the
939       "on_ready" method, and obtain the result using "get".
940
941        my $f = foperation( foo => "something" );
942
943        $f->on_ready( sub {
944           my $f = shift;
945           say "The operation returned: ", $f->get;
946        } );
947
948   Indicating Success or Failure
949       Because the stored exception value of a failed future may not be false,
950       the "failure" method can be used in a conditional statement to detect
951       success or failure.
952
953        my $f = foperation( foo => "something" );
954
955        $f->on_ready( sub {
956           my $f = shift;
957           if( not my $e = $f->failure ) {
958              say "The operation succeeded with: ", $f->get;
959           }
960           else {
961              say "The operation failed with: ", $e;
962           }
963        } );
964
965       By using "not" in the condition, the order of the "if" blocks can be
966       arranged to put the successful case first, similar to a "try"/"catch"
967       block.
968
969       Because the "get" method re-raises the passed exception if the future
970       failed, it can be used to control a "try"/"catch" block directly. (This
971       is sometimes called Exception Hoisting).
972
973        use Try::Tiny;
974
975        $f->on_ready( sub {
976           my $f = shift;
977           try {
978              say "The operation succeeded with: ", $f->get;
979           }
980           catch {
981              say "The operation failed with: ", $_;
982           };
983        } );
984
985       Even neater still may be the separate use of the "on_done" and
986       "on_fail" methods.
987
988        $f->on_done( sub {
989           my @result = @_;
990           say "The operation succeeded with: ", @result;
991        } );
992        $f->on_fail( sub {
993           my ( $failure ) = @_;
994           say "The operation failed with: $failure";
995        } );
996
997   Immediate Futures
998       Because the "done" method returns the future object itself, it can be
999       used to generate a "Future" that is immediately ready with a result.
1000       This can also be used as a class method.
1001
1002        my $f = Future->done( $value );
1003
1004       Similarly, the "fail" and "die" methods can be used to generate a
1005       "Future" that is immediately failed.
1006
1007        my $f = Future->die( "This is never going to work" );
1008
1009       This could be considered similarly to a "die" call.
1010
1011       An "eval{}" block can be used to turn a "Future"-returning function
1012       that might throw an exception, into a "Future" that would indicate this
1013       failure.
1014
1015        my $f = eval { function() } || Future->fail( $@ );
1016
1017       This is neater handled by the "call" class method, which wraps the call
1018       in an "eval{}" block and tests the result:
1019
1020        my $f = Future->call( \&function );
1021
1022   Sequencing
1023       The "then" method can be used to create simple chains of dependent
1024       tasks, each one executing and returning a "Future" when the previous
1025       operation succeeds.
1026
1027        my $f = do_first()
1028                   ->then( sub {
1029                      return do_second();
1030                   })
1031                   ->then( sub {
1032                      return do_third();
1033                   });
1034
1035       The result of the $f future itself will be the result of the future
1036       returned by the final function, if none of them failed. If any of them
1037       fails it will fail with the same failure. This can be considered
1038       similar to normal exception handling in synchronous code; the first
1039       time a function call throws an exception, the subsequent calls are not
1040       made.
1041
1042   Merging Control Flow
1043       A "wait_all" future may be used to resynchronise control flow, while
1044       waiting for multiple concurrent operations to finish.
1045
1046        my $f1 = foperation( foo => "something" );
1047        my $f2 = foperation( bar => "something else" );
1048
1049        my $f = Future->wait_all( $f1, $f2 );
1050
1051        $f->on_ready( sub {
1052           say "Operations are ready:";
1053           say "  foo: ", $f1->get;
1054           say "  bar: ", $f2->get;
1055        } );
1056
1057       This provides an ability somewhat similar to "CPS::kpar()" or
1058       Async::MergePoint.
1059

KNOWN ISSUES

1061   Cancellation of Non-Final Sequence Futures
1062       The behaviour of future cancellation still has some unanswered
1063       questions regarding how to handle the situation where a future is
1064       cancelled that has a sequence future constructed from it.
1065
1066       In particular, it is unclear in each of the following examples what the
1067       behaviour of $f2 should be, were $f1 to be cancelled:
1068
1069        $f2 = $f1->then( sub { ... } ); # plus related ->then_with_f, ...
1070
1071        $f2 = $f1->else( sub { ... } ); # plus related ->else_with_f, ...
1072
1073        $f2 = $f1->followed_by( sub { ... } );
1074
1075       In the "then"-style case it is likely that this situation should be
1076       treated as if $f1 had failed, perhaps with some special message. The
1077       "else"-style case is more complex, because it may be that the entire
1078       operation should still fail, or it may be that the cancellation of $f1
1079       should again be treated simply as a special kind of failure, and the
1080       "else" logic run as normal.
1081
1082       To be specific; in each case it is unclear what happens if the first
1083       future is cancelled, while the second one is still waiting on it. The
1084       semantics for "normal" top-down cancellation of $f2 and how it affects
1085       $f1 are already clear and defined.
1086
1087   Cancellation of Divergent Flow
1088       A further complication of cancellation comes from the case where a
1089       given future is reused multiple times for multiple sequences or
1090       convergent trees.
1091
1092       In particular, it is in clear in each of the following examples what
1093       the behaviour of $f2 should be, were $f1 to be cancelled:
1094
1095        my $f_initial = Future->new; ...
1096        my $f1 = $f_initial->then( ... );
1097        my $f2 = $f_initial->then( ... );
1098
1099        my $f1 = Future->needs_all( $f_initial );
1100        my $f2 = Future->needs_all( $f_initial );
1101
1102       The point of cancellation propagation is to trace backwards through
1103       stages of some larger sequence of operations that now no longer need to
1104       happen, because the final result is no longer required. But in each of
1105       these cases, just because $f1 has been cancelled, the initial future
1106       $f_initial is still required because there is another future ($f2) that
1107       will still require its result.
1108
1109       Initially it would appear that some kind of reference-counting
1110       mechanism could solve this question, though that itself is further
1111       complicated by the "on_ready" handler and its variants.
1112
1113       It may simply be that a comprehensive useful set of cancellation
1114       semantics can't be universally provided to cover all cases; and that
1115       some use-cases at least would require the application logic to give
1116       extra information to its "Future" objects on how they should wire up
1117       the cancel propagation logic.
1118
1119       Both of these cancellation issues are still under active design
1120       consideration; see the discussion on RT96685 for more information
1121       (<https://rt.cpan.org/Ticket/Display.html?id=96685>).
1122

SEE ALSO

1124       ·   Promises - an implementation of the "Promise/A+" pattern for
1125           asynchronous programming
1126
1127       ·   curry - Create automatic curried method call closures for any class
1128           or object
1129
1130       ·   "The Past, The Present and The Future" - slides from a talk given
1131           at the London Perl Workshop, 2012.
1132
1133           <https://docs.google.com/presentation/d/1UkV5oLcTOOXBXPh8foyxko4PR28_zU_aVx6gBms7uoo/edit>
1134
1135       ·   "Futures advent calendar 2013"
1136
1137           <http://leonerds-code.blogspot.co.uk/2013/12/futures-advent-day-1.html>
1138
1139       ·   "Asynchronous Programming with Futures" - YAPC::EU 2014
1140
1141           <https://www.youtube.com/watch?v=u9dZgFM6FtE>
1142

TODO

1144       ·   Consider the ability to pass the constructor an "await" CODEref,
1145           instead of needing to use a subclass. This might simplify
1146           async/etc.. implementations, and allows the reuse of the idea of
1147           subclassing to extend the abilities of "Future" itself - for
1148           example to allow a kind of Future that can report incremental
1149           progress.
1150

AUTHOR

1152       Paul Evans <leonerd@leonerd.org.uk>
1153
1154
1155
1156perl v5.28.0                      2018-07-14                         Future(3)
Impressum