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 overrides the "block_until_ready" method, this will be
110       called by "get" and "failure" if the instance is still pending.
111
112       In most cases this should allow future-returning modules to be used as
113       if they were blocking call/return-style modules, by simply appending a
114       "get" call to the function or method calls.
115
116          my ( $results, $here ) = future_returning_function( @args )->get;
117
118   DEBUGGING
119       By the time a "Future" object is destroyed, it ought to have been
120       completed or cancelled. By enabling debug tracing of objects, this fact
121       can be checked.  If a future object is destroyed without having been
122       completed or cancelled, a warning message is printed.
123
124          $ PERL_FUTURE_DEBUG=1 perl -MFuture -E 'my $f = Future->new'
125          Future=HASH(0xaa61f8) was constructed at -e line 1 and was lost near -e line 0 before it was ready.
126
127       Note that due to a limitation of perl's "caller" function within a
128       "DESTROY" destructor method, the exact location of the leak cannot be
129       accurately determined. Often the leak will occur due to falling out of
130       scope by returning from a function; in this case the leak location may
131       be reported as being the line following the line calling that function.
132
133          $ PERL_FUTURE_DEBUG=1 perl -MFuture
134          sub foo {
135             my $f = Future->new;
136          }
137
138          foo();
139          print "Finished\n";
140
141          Future=HASH(0x14a2220) was constructed at - line 2 and was lost near - line 6 before it was ready.
142          Finished
143
144       A warning is also printed in debug mode if a "Future" object is
145       destroyed that completed with a failure, but the object believes that
146       failure has not been reported anywhere.
147
148          $ PERL_FUTURE_DEBUG=1 perl -Mblib -MFuture -E 'my $f = Future->fail("Oops")'
149          Future=HASH(0xac98f8) was constructed at -e line 1 and was lost near -e line 0 with an unreported failure of: Oops
150
151       Such a failure is considered reported if the "get" or "failure" methods
152       are called on it, or it had at least one "on_ready" or "on_fail"
153       callback, or its failure is propagated to another "Future" instance (by
154       a sequencing or converging method).
155

CONSTRUCTORS

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

METHODS

211       As there are a lare number of methods on this class, they are
212       documented here in several sections.
213

INSPECTION METHODS

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

IMPLEMENTATION METHODS

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

USER METHODS

322       These methods would primarily be used by users of asynchronous
323       interfaces, on objects returned by such an interface.
324
325   on_ready
326          $future->on_ready( $code )
327
328       If the future is not yet ready, adds a callback to be invoked when the
329       future is ready. If the future is already ready, invokes it
330       immediately.
331
332       In either case, the callback will be passed the future object itself.
333       The invoked code can then obtain the list of results by calling the
334       "get" method.
335
336          $on_ready->( $future )
337
338       If passed another "Future" instance, the passed instance will have its
339       "done", "fail" or "cancel" methods invoked when the original future
340       completes successfully, fails, or is cancelled respectively.
341
342       Returns the $future.
343
344   get
345          @result = $future->get
346
347          $result = $future->get
348
349       If the future is ready and completed successfully, returns the list of
350       results that had earlier been given to the "done" method on a leaf
351       future, or the list of component futures it was waiting for on a
352       convergent future. In scalar context it returns just the first result
353       value.
354
355       If the future is ready but failed, this method raises as an exception
356       the failure that was given to the "fail" method. If additional details
357       were given to the "fail" method, an exception object is constructed to
358       wrap them of type Future::Exception.
359
360       If the future was cancelled an exception is thrown.
361
362       If it is not yet ready then "block_until_ready" is invoked to wait for
363       a ready state.
364
365   block_until_ready
366          $f = $f->block_until_ready
367
368       Since version 0.40.
369
370       Blocks until the future instance is no longer pending.
371
372       Returns the invocant future itself, so it is useful for chaining.
373
374       Usually, calling code would either force the future using "get", or use
375       either "then" chaining or "async/await" syntax to wait for results.
376       This method is useful in cases where the exception-throwing part of
377       "get" is not required, perhaps because other code will be testing the
378       result using "is_done" or similar.
379
380          if( $f->block_until_ready->is_done ) {
381             ...
382          }
383
384       This method is intended for subclasses to override, but a default
385       implementation for back-compatibility purposes is provided which calls
386       the "await" method. If the future is not yet ready, attempts to wait
387       for an eventual result by using the underlying "await" method, which
388       subclasses should provide. The default implementation will throw an
389       exception if called on a still-pending instance that does not provide
390       an "await" method.
391
392   unwrap
393          @values = Future->unwrap( @values )
394
395       Since version 0.26.
396
397       If given a single argument which is a "Future" reference, this method
398       will call "get" on it and return the result. Otherwise, it returns the
399       list of values directly in list context, or the first value in scalar.
400       Since it involves an implicit blocking wait, this method can only be
401       used on immediate futures or subclasses that implement
402       "block_until_ready".
403
404       This will ensure that an outgoing argument is definitely not a
405       "Future", and may be useful in such cases as adapting synchronous code
406       to fit asynchronous libraries that return "Future" instances.
407
408   on_done
409          $future->on_done( $code )
410
411       If the future is not yet ready, adds a callback to be invoked when the
412       future is ready, if it completes successfully. If the future completed
413       successfully, invokes it immediately. If it failed or was cancelled, it
414       is not invoked at all.
415
416       The callback will be passed the result passed to the "done" method.
417
418          $on_done->( @result )
419
420       If passed another "Future" instance, the passed instance will have its
421       "done" method invoked when the original future completes successfully.
422
423       Returns the $future.
424
425   failure
426          $exception = $future->failure
427
428          $exception, $category, @details = $future->failure
429
430       If the future is ready, returns the exception passed to the "fail"
431       method or "undef" if the future completed successfully via the "done"
432       method.
433
434       If it is not yet ready then "block_until_ready" is invoked to wait for
435       a ready state.
436
437       If called in list context, will additionally yield the category name
438       and list of the details provided to the "fail" method.
439
440       Because the exception value must be true, this can be used in a simple
441       "if" statement:
442
443          if( my $exception = $future->failure ) {
444             ...
445          }
446          else {
447             my @result = $future->get;
448             ...
449          }
450
451   on_fail
452          $future->on_fail( $code )
453
454       If the future is not yet ready, adds a callback to be invoked when the
455       future is ready, if it fails. If the future has already failed, invokes
456       it immediately. If it completed successfully or was cancelled, it is
457       not invoked at all.
458
459       The callback will be passed the exception and other details passed to
460       the "fail" method.
461
462          $on_fail->( $exception, $category, @details )
463
464       If passed another "Future" instance, the passed instance will have its
465       "fail" method invoked when the original future fails.
466
467       To invoke a "done" method on a future when another one fails, use a
468       CODE reference:
469
470          $future->on_fail( sub { $f->done( @_ ) } );
471
472       Returns the $future.
473
474   cancel
475          $future->cancel
476
477       Requests that the future be cancelled, immediately marking it as ready.
478       This will invoke all of the code blocks registered by "on_cancel", in
479       the reverse order. When called on a convergent future, all its
480       component futures are also cancelled. It is not an error to attempt to
481       cancel a future that is already complete or cancelled; it simply has no
482       effect.
483
484       Returns the $future.
485

SEQUENCING METHODS

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

CONVERGENT FUTURES

725       The following constructors all take a list of component futures, and
726       return a new future whose readiness somehow depends on the readiness of
727       those components. The first derived class component future will be used
728       as the prototype for constructing the return value, so it respects
729       subclassing correctly, or failing that a plain "Future".
730
731   wait_all
732          $future = Future->wait_all( @subfutures )
733
734       Returns a new "Future" instance that will indicate it is ready once all
735       of the sub future objects given to it indicate that they are ready,
736       either by success, failure or cancellation. Its result will be a list
737       of its component futures.
738
739       When given an empty list this constructor returns a new immediately-
740       done future.
741
742       This constructor would primarily be used by users of asynchronous
743       interfaces.
744
745   wait_any
746          $future = Future->wait_any( @subfutures )
747
748       Returns a new "Future" instance that will indicate it is ready once any
749       of the sub future objects given to it indicate that they are ready,
750       either by success or failure. Any remaining component futures that are
751       not yet ready will be cancelled. Its result will be the result of the
752       first component future that was ready; either success or failure. Any
753       component futures that are cancelled are ignored, apart from the final
754       component left; at which point the result will be a failure.
755
756       When given an empty list this constructor returns an immediately-failed
757       future.
758
759       This constructor would primarily be used by users of asynchronous
760       interfaces.
761
762   needs_all
763          $future = Future->needs_all( @subfutures )
764
765       Returns a new "Future" instance that will indicate it is ready once all
766       of the sub future objects given to it indicate that they have completed
767       successfully, or when any of them indicates that they have failed. If
768       any sub future fails, then this will fail immediately, and the
769       remaining subs not yet ready will be cancelled. Any component futures
770       that are cancelled will cause an immediate failure of the result.
771
772       If successful, its result will be a concatenated list of the results of
773       all its component futures, in corresponding order. If it fails, its
774       failure will be that of the first component future that failed. To
775       access each component future's results individually, use
776       "done_futures".
777
778       When given an empty list this constructor returns a new immediately-
779       done future.
780
781       This constructor would primarily be used by users of asynchronous
782       interfaces.
783
784   needs_any
785          $future = Future->needs_any( @subfutures )
786
787       Returns a new "Future" instance that will indicate it is ready once any
788       of the sub future objects given to it indicate that they have completed
789       successfully, or when all of them indicate that they have failed. If
790       any sub future succeeds, then this will succeed immediately, and the
791       remaining subs not yet ready will be cancelled. Any component futures
792       that are cancelled are ignored, apart from the final component left; at
793       which point the result will be a failure.
794
795       If successful, its result will be that of the first component future
796       that succeeded. If it fails, its failure will be that of the last
797       component future to fail. To access the other failures, use
798       "failed_futures".
799
800       Normally when this future completes successfully, only one of its
801       component futures will be done. If it is constructed with multiple that
802       are already done however, then all of these will be returned from
803       "done_futures". Users should be careful to still check all the results
804       from "done_futures" in that case.
805
806       When given an empty list this constructor returns an immediately-failed
807       future.
808
809       This constructor would primarily be used by users of asynchronous
810       interfaces.
811

METHODS ON CONVERGENT FUTURES

813       The following methods apply to convergent (i.e. non-leaf) futures, to
814       access the component futures stored by it.
815
816   pending_futures
817          @f = $future->pending_futures
818
819   ready_futures
820          @f = $future->ready_futures
821
822   done_futures
823          @f = $future->done_futures
824
825   failed_futures
826          @f = $future->failed_futures
827
828   cancelled_futures
829          @f = $future->cancelled_futures
830
831       Return a list of all the pending, ready, done, failed, or cancelled
832       component futures. In scalar context, each will yield the number of
833       such component futures.
834

TRACING METHODS

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

EXAMPLES

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

KNOWN ISSUES

1096   Cancellation of Non-Final Sequence Futures
1097       The behaviour of future cancellation still has some unanswered
1098       questions regarding how to handle the situation where a future is
1099       cancelled that has a sequence future constructed from it.
1100
1101       In particular, it is unclear in each of the following examples what the
1102       behaviour of $f2 should be, were $f1 to be cancelled:
1103
1104          $f2 = $f1->then( sub { ... } ); # plus related ->then_with_f, ...
1105
1106          $f2 = $f1->else( sub { ... } ); # plus related ->else_with_f, ...
1107
1108          $f2 = $f1->followed_by( sub { ... } );
1109
1110       In the "then"-style case it is likely that this situation should be
1111       treated as if $f1 had failed, perhaps with some special message. The
1112       "else"-style case is more complex, because it may be that the entire
1113       operation should still fail, or it may be that the cancellation of $f1
1114       should again be treated simply as a special kind of failure, and the
1115       "else" logic run as normal.
1116
1117       To be specific; in each case it is unclear what happens if the first
1118       future is cancelled, while the second one is still waiting on it. The
1119       semantics for "normal" top-down cancellation of $f2 and how it affects
1120       $f1 are already clear and defined.
1121
1122   Cancellation of Divergent Flow
1123       A further complication of cancellation comes from the case where a
1124       given future is reused multiple times for multiple sequences or
1125       convergent trees.
1126
1127       In particular, it is in clear in each of the following examples what
1128       the behaviour of $f2 should be, were $f1 to be cancelled:
1129
1130          my $f_initial = Future->new; ...
1131          my $f1 = $f_initial->then( ... );
1132          my $f2 = $f_initial->then( ... );
1133
1134          my $f1 = Future->needs_all( $f_initial );
1135          my $f2 = Future->needs_all( $f_initial );
1136
1137       The point of cancellation propagation is to trace backwards through
1138       stages of some larger sequence of operations that now no longer need to
1139       happen, because the final result is no longer required. But in each of
1140       these cases, just because $f1 has been cancelled, the initial future
1141       $f_initial is still required because there is another future ($f2) that
1142       will still require its result.
1143
1144       Initially it would appear that some kind of reference-counting
1145       mechanism could solve this question, though that itself is further
1146       complicated by the "on_ready" handler and its variants.
1147
1148       It may simply be that a comprehensive useful set of cancellation
1149       semantics can't be universally provided to cover all cases; and that
1150       some use-cases at least would require the application logic to give
1151       extra information to its "Future" objects on how they should wire up
1152       the cancel propagation logic.
1153
1154       Both of these cancellation issues are still under active design
1155       consideration; see the discussion on RT96685 for more information
1156       (<https://rt.cpan.org/Ticket/Display.html?id=96685>).
1157

SEE ALSO

1159       ·   Future::AsyncAwait - deferred subroutine syntax for futures
1160
1161           Provides a neat syntax extension for writing future-based code.
1162
1163       ·   Future::IO - Future-returning IO methods
1164
1165           Provides methods similar to core IO functions, which yield results
1166           by Futures.
1167
1168       ·   Promises - an implementation of the "Promise/A+" pattern for
1169           asynchronous programming
1170
1171           A different alternative implementation of a similar idea.
1172
1173       ·   curry - Create automatic curried method call closures for any class
1174           or object
1175
1176       ·   "The Past, The Present and The Future" - slides from a talk given
1177           at the London Perl Workshop, 2012.
1178
1179           <https://docs.google.com/presentation/d/1UkV5oLcTOOXBXPh8foyxko4PR28_zU_aVx6gBms7uoo/edit>
1180
1181       ·   "Futures advent calendar 2013"
1182
1183           <http://leonerds-code.blogspot.co.uk/2013/12/futures-advent-day-1.html>
1184
1185       ·   "Asynchronous Programming with Futures" - YAPC::EU 2014
1186
1187           <https://www.youtube.com/watch?v=u9dZgFM6FtE>
1188

TODO

1190       ·   Consider the ability to pass the constructor a "block" CODEref,
1191           instead of needing to use a subclass. This might simplify
1192           async/etc.. implementations, and allows the reuse of the idea of
1193           subclassing to extend the abilities of "Future" itself - for
1194           example to allow a kind of Future that can report incremental
1195           progress.
1196

AUTHOR

1198       Paul Evans <leonerd@leonerd.org.uk>
1199
1200
1201
1202perl v5.30.0                      2019-07-26                         Future(3)
Impressum