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

SUBCLASSING METHODS

886       These methods are not intended for end-users of "Future" instances, but
887       instead provided for authors of classes that subclass from "Future"
888       itself.
889
890   set_udata
891          $future = $future->set_udata( $name, $value )
892
893       Stores a Perl value within the instance, under the given name.
894       Subclasses can use this to store extra data that the implementation may
895       require.
896
897       This is a safer version of attempting to use the $future instance
898       itself as a hash reference.
899
900   udata
901          $value = $future->get_udata( $name )
902
903       Returns a Perl value from the instance that was previously set with
904       "set_udata".
905

TRACING METHODS

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

EXAMPLES

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

KNOWN ISSUES

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

SEE ALSO

1230       •   Future::AsyncAwait - deferred subroutine syntax for futures
1231
1232           Provides a neat syntax extension for writing future-based code.
1233
1234       •   Future::IO - Future-returning IO methods
1235
1236           Provides methods similar to core IO functions, which yield results
1237           by Futures.
1238
1239       •   Promises - an implementation of the "Promise/A+" pattern for
1240           asynchronous programming
1241
1242           A different alternative implementation of a similar idea.
1243
1244       •   curry - Create automatic curried method call closures for any class
1245           or object
1246
1247       •   "The Past, The Present and The Future" - slides from a talk given
1248           at the London Perl Workshop, 2012.
1249
1250           <https://docs.google.com/presentation/d/1UkV5oLcTOOXBXPh8foyxko4PR28_zU_aVx6gBms7uoo/edit>
1251
1252       •   "Futures advent calendar 2013"
1253
1254           <http://leonerds-code.blogspot.co.uk/2013/12/futures-advent-day-1.html>
1255
1256       •   "Asynchronous Programming with Futures" - YAPC::EU 2014
1257
1258           <https://www.youtube.com/watch?v=u9dZgFM6FtE>
1259

TODO

1261       •   Consider the ability to pass the constructor a "block" CODEref,
1262           instead of needing to use a subclass. This might simplify
1263           async/etc.. implementations, and allows the reuse of the idea of
1264           subclassing to extend the abilities of "Future" itself - for
1265           example to allow a kind of Future that can report incremental
1266           progress.
1267

AUTHOR

1269       Paul Evans <leonerd@leonerd.org.uk>
1270
1271
1272
1273perl v5.36.0                      2023-01-20                         Future(3)
Impressum