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
156   Future::AsyncAwait::Awaitable ROLE
157       Since version 0.43 this module provides the
158       Future::AsyncAwait::Awaitable API. Subclass authors should note that
159       several of the API methods are provided by special optimised internal
160       methods, which may require overriding in your subclass if your
161       internals are different from that of this module.
162

CONSTRUCTORS

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

METHODS

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

INSPECTION METHODS

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

IMPLEMENTATION METHODS

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

USER METHODS

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

SEQUENCING METHODS

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

CONVERGENT FUTURES

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

METHODS ON CONVERGENT FUTURES

824       The following methods apply to convergent (i.e. non-leaf) futures, to
825       access the component futures stored by it.
826
827   pending_futures
828          @f = $future->pending_futures
829
830   ready_futures
831          @f = $future->ready_futures
832
833   done_futures
834          @f = $future->done_futures
835
836   failed_futures
837          @f = $future->failed_futures
838
839   cancelled_futures
840          @f = $future->cancelled_futures
841
842       Return a list of all the pending, ready, done, failed, or cancelled
843       component futures. In scalar context, each will yield the number of
844       such component futures.
845

TRACING METHODS

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

EXAMPLES

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

KNOWN ISSUES

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

SEE ALSO

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

TODO

1201       ·   Consider the ability to pass the constructor a "block" CODEref,
1202           instead of needing to use a subclass. This might simplify
1203           async/etc.. implementations, and allows the reuse of the idea of
1204           subclassing to extend the abilities of "Future" itself - for
1205           example to allow a kind of Future that can report incremental
1206           progress.
1207

AUTHOR

1209       Paul Evans <leonerd@leonerd.org.uk>
1210
1211
1212
1213perl v5.30.1                      2020-01-30                         Future(3)
Impressum