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 "await" method, this will be called by
110       "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       Since version 0.45: this method is also available under the name
279       "resolve".
280
281   fail
282          $future->fail( $exception, $category, @details )
283
284       Marks that the leaf future has failed, and provides an exception value.
285       This exception will be thrown by the "get" method if called.
286
287       The exception must evaluate as a true value; false exceptions are not
288       allowed.  A failure category name and other further details may be
289       provided that will be returned by the "failure" method in list context.
290
291       If the future is already cancelled, this request is ignored. If the
292       future is already complete with a result or a failure, an exception is
293       thrown.
294
295       If passed a Future::Exception instance (i.e. an object previously
296       thrown by the "get"), the additional details will be preserved. This
297       allows the additional details to be transparently preserved by such
298       code as
299
300          ...
301          catch {
302             return Future->fail($@);
303          }
304
305       Since version 0.45: this method is also available under the name
306       "reject".
307
308   die
309          $future->die( $message, $category, @details )
310
311       Since version 0.09.
312
313       A convenient wrapper around "fail". If the exception is a non-reference
314       that does not end in a linefeed, its value will be extended by the file
315       and line number of the caller, similar to the logic that "die" uses.
316
317       Returns the $future.
318
319   on_cancel
320          $future->on_cancel( $code )
321
322       If the future is not yet ready, adds a callback to be invoked if the
323       future is cancelled by the "cancel" method. If the future is already
324       ready the method is ignored.
325
326       If the future is later cancelled, the callbacks will be invoked in the
327       reverse order to that in which they were registered.
328
329          $on_cancel->( $future )
330
331       If passed another "Future" instance, the passed instance will be
332       cancelled when the original future is cancelled. In this case, the
333       reference is only strongly held while the target future remains
334       pending. If it becomes ready, then there is no point trying to cancel
335       it, and so it is removed from the originating future's cancellation
336       list.
337

USER METHODS

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

SEQUENCING METHODS

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

CONVERGENT FUTURES

775       The following constructors all take a list of component futures, and
776       return a new future whose readiness somehow depends on the readiness of
777       those components. The first derived class component future will be used
778       as the prototype for constructing the return value, so it respects
779       subclassing correctly, or failing that a plain "Future".
780
781   wait_all
782          $future = Future->wait_all( @subfutures )
783
784       Returns a new "Future" instance that will indicate it is ready once all
785       of the sub future objects given to it indicate that they are ready,
786       either by success, failure or cancellation. Its result will be a list
787       of its component 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   wait_any
796          $future = Future->wait_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 are ready,
800       either by success or failure. Any remaining component futures that are
801       not yet ready will be cancelled. Its result will be the result of the
802       first component future that was ready; either success or failure. Any
803       component futures that are cancelled are ignored, apart from the final
804       component left; at which point the result will be a failure.
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
812   needs_all
813          $future = Future->needs_all( @subfutures )
814
815       Returns a new "Future" instance that will indicate it is ready once all
816       of the sub future objects given to it indicate that they have completed
817       successfully, or when any of them indicates that they have failed. If
818       any sub future fails, then this will fail immediately, and the
819       remaining subs not yet ready will be cancelled. Any component futures
820       that are cancelled will cause an immediate failure of the result.
821
822       If successful, its result will be a concatenated list of the results of
823       all its component futures, in corresponding order. If it fails, its
824       failure will be that of the first component future that failed. To
825       access each component future's results individually, use
826       "done_futures".
827
828       When given an empty list this constructor returns a new immediately-
829       done future.
830
831       This constructor would primarily be used by users of asynchronous
832       interfaces.
833
834   needs_any
835          $future = Future->needs_any( @subfutures )
836
837       Returns a new "Future" instance that will indicate it is ready once any
838       of the sub future objects given to it indicate that they have completed
839       successfully, or when all of them indicate that they have failed. If
840       any sub future succeeds, then this will succeed immediately, and the
841       remaining subs not yet ready will be cancelled. Any component futures
842       that are cancelled are ignored, apart from the final component left; at
843       which point the result will be a failure.
844
845       If successful, its result will be that of the first component future
846       that succeeded. If it fails, its failure will be that of the last
847       component future to fail. To access the other failures, use
848       "failed_futures".
849
850       Normally when this future completes successfully, only one of its
851       component futures will be done. If it is constructed with multiple that
852       are already done however, then all of these will be returned from
853       "done_futures". Users should be careful to still check all the results
854       from "done_futures" in that case.
855
856       When given an empty list this constructor returns an immediately-failed
857       future.
858
859       This constructor would primarily be used by users of asynchronous
860       interfaces.
861

METHODS ON CONVERGENT FUTURES

863       The following methods apply to convergent (i.e. non-leaf) futures, to
864       access the component futures stored by it.
865
866   pending_futures
867          @f = $future->pending_futures
868
869   ready_futures
870          @f = $future->ready_futures
871
872   done_futures
873          @f = $future->done_futures
874
875   failed_futures
876          @f = $future->failed_futures
877
878   cancelled_futures
879          @f = $future->cancelled_futures
880
881       Return a list of all the pending, ready, done, failed, or cancelled
882       component futures. In scalar context, each will yield the number of
883       such component futures.
884

TRACING METHODS

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

EXAMPLES

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

KNOWN ISSUES

1146   Cancellation of Non-Final Sequence Futures
1147       The behaviour of future cancellation still has some unanswered
1148       questions regarding how to handle the situation where a future is
1149       cancelled that has a sequence future constructed from it.
1150
1151       In particular, it is unclear in each of the following examples what the
1152       behaviour of $f2 should be, were $f1 to be cancelled:
1153
1154          $f2 = $f1->then( sub { ... } ); # plus related ->then_with_f, ...
1155
1156          $f2 = $f1->else( sub { ... } ); # plus related ->else_with_f, ...
1157
1158          $f2 = $f1->followed_by( sub { ... } );
1159
1160       In the "then"-style case it is likely that this situation should be
1161       treated as if $f1 had failed, perhaps with some special message. The
1162       "else"-style case is more complex, because it may be that the entire
1163       operation should still fail, or it may be that the cancellation of $f1
1164       should again be treated simply as a special kind of failure, and the
1165       "else" logic run as normal.
1166
1167       To be specific; in each case it is unclear what happens if the first
1168       future is cancelled, while the second one is still waiting on it. The
1169       semantics for "normal" top-down cancellation of $f2 and how it affects
1170       $f1 are already clear and defined.
1171
1172   Cancellation of Divergent Flow
1173       A further complication of cancellation comes from the case where a
1174       given future is reused multiple times for multiple sequences or
1175       convergent trees.
1176
1177       In particular, it is in clear in each of the following examples what
1178       the behaviour of $f2 should be, were $f1 to be cancelled:
1179
1180          my $f_initial = Future->new; ...
1181          my $f1 = $f_initial->then( ... );
1182          my $f2 = $f_initial->then( ... );
1183
1184          my $f1 = Future->needs_all( $f_initial );
1185          my $f2 = Future->needs_all( $f_initial );
1186
1187       The point of cancellation propagation is to trace backwards through
1188       stages of some larger sequence of operations that now no longer need to
1189       happen, because the final result is no longer required. But in each of
1190       these cases, just because $f1 has been cancelled, the initial future
1191       $f_initial is still required because there is another future ($f2) that
1192       will still require its result.
1193
1194       Initially it would appear that some kind of reference-counting
1195       mechanism could solve this question, though that itself is further
1196       complicated by the "on_ready" handler and its variants.
1197
1198       It may simply be that a comprehensive useful set of cancellation
1199       semantics can't be universally provided to cover all cases; and that
1200       some use-cases at least would require the application logic to give
1201       extra information to its "Future" objects on how they should wire up
1202       the cancel propagation logic.
1203
1204       Both of these cancellation issues are still under active design
1205       consideration; see the discussion on RT96685 for more information
1206       (<https://rt.cpan.org/Ticket/Display.html?id=96685>).
1207

SEE ALSO

1209       •   Future::AsyncAwait - deferred subroutine syntax for futures
1210
1211           Provides a neat syntax extension for writing future-based code.
1212
1213       •   Future::IO - Future-returning IO methods
1214
1215           Provides methods similar to core IO functions, which yield results
1216           by Futures.
1217
1218       •   Promises - an implementation of the "Promise/A+" pattern for
1219           asynchronous programming
1220
1221           A different alternative implementation of a similar idea.
1222
1223       •   curry - Create automatic curried method call closures for any class
1224           or object
1225
1226       •   "The Past, The Present and The Future" - slides from a talk given
1227           at the London Perl Workshop, 2012.
1228
1229           <https://docs.google.com/presentation/d/1UkV5oLcTOOXBXPh8foyxko4PR28_zU_aVx6gBms7uoo/edit>
1230
1231       •   "Futures advent calendar 2013"
1232
1233           <http://leonerds-code.blogspot.co.uk/2013/12/futures-advent-day-1.html>
1234
1235       •   "Asynchronous Programming with Futures" - YAPC::EU 2014
1236
1237           <https://www.youtube.com/watch?v=u9dZgFM6FtE>
1238

TODO

1240       •   Consider the ability to pass the constructor a "block" CODEref,
1241           instead of needing to use a subclass. This might simplify
1242           async/etc.. implementations, and allows the reuse of the idea of
1243           subclassing to extend the abilities of "Future" itself - for
1244           example to allow a kind of Future that can report incremental
1245           progress.
1246

AUTHOR

1248       Paul Evans <leonerd@leonerd.org.uk>
1249
1250
1251
1252perl v5.36.0                      2022-07-22                         Future(3)
Impressum