1Future(3) User Contributed Perl Documentation Future(3)
2
3
4
6 "Future" - represent an operation awaiting completion
7
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
22 A "Future" object represents an operation that is currently in
23 progress, or has recently completed. It can be used in a variety of
24 ways to manage the flow of control, and data, through an asynchronous
25 program.
26
27 Some futures represent a single operation and are explicitly marked as
28 ready by calling the "done" or "fail" methods. These are called "leaf"
29 futures here, and are returned by the "new" constructor.
30
31 Other futures represent a collection of sub-tasks, and are implicitly
32 marked as ready depending on the readiness of their component futures
33 as required. These are called "convergent" futures here as they
34 converge control and data-flow back into one place. These are the ones
35 returned by the various "wait_*" and "need_*" constructors.
36
37 It is intended that library functions that perform asynchronous
38 operations would use future objects to represent outstanding
39 operations, and allow their calling programs to control or wait for
40 these operations to complete. The implementation and the user of such
41 an interface would typically make use of different methods on the
42 class. The methods below are documented in two sections; those of
43 interest to each side of the interface.
44
45 It should be noted however, that this module does not in any way
46 provide an actual mechanism for performing this asynchronous activity;
47 it merely provides a way to create objects that can be used for control
48 and data flow around those operations. It allows such code to be
49 written in a neater, forward-reading manner, and simplifies many common
50 patterns that are often involved in such situations.
51
52 See also Future::Utils which contains useful loop-constructing
53 functions, to run a future-returning function repeatedly in a loop.
54
55 Unless otherwise noted, the following methods require at least version
56 0.08.
57
58 FAILURE CATEGORIES
59 While not directly required by "Future" or its related modules, a
60 growing convention of "Future"-using code is to encode extra semantics
61 in the arguments given to the "fail" method, to represent different
62 kinds of failure.
63
64 The convention is that after the initial message string as the first
65 required argument (intended for display to humans), the second argument
66 is a short lowercase string that relates in some way to the kind of
67 failure that occurred. Following this is a list of details about that
68 kind of failure, whose exact arrangement or structure are determined by
69 the failure category. For example, IO::Async and Net::Async::HTTP use
70 this convention to indicate at what stage a given HTTP request has
71 failed:
72
73 ->fail( $message, http => ... ) # an HTTP-level error during protocol
74 ->fail( $message, connect => ... ) # a TCP-level failure to connect a
75 # socket
76 ->fail( $message, resolve => ... ) # a resolver (likely DNS) failure
77 # to resolve a hostname
78
79 By following this convention, a module remains consistent with other
80 "Future"-based modules, and makes it easy for program logic to
81 gracefully handle and manage failures by use of the "catch" method.
82
83 SUBCLASSING
84 This class easily supports being subclassed to provide extra behavior,
85 such as giving the "get" method the ability to block and wait for
86 completion. This may be useful to provide "Future" subclasses with
87 event systems, or similar.
88
89 Each method that returns a new future object will use the invocant to
90 construct its return value. If the constructor needs to perform per-
91 instance setup it can override the "new" method, and take context from
92 the given instance.
93
94 sub new
95 {
96 my $proto = shift;
97 my $self = $proto->SUPER::new;
98
99 if( ref $proto ) {
100 # Prototype was an instance
101 }
102 else {
103 # Prototype was a class
104 }
105
106 return $self;
107 }
108
109 If an instance provides a method called "await", this will be called by
110 the "get" and "failure" methods if the instance is pending.
111
112 $f->await
113
114 In most cases this should allow future-returning modules to be used as
115 if they were blocking call/return-style modules, by simply appending a
116 "get" call to the function or method calls.
117
118 my ( $results, $here ) = future_returning_function( @args )->get;
119
120 The examples directory in the distribution contains some examples of
121 how futures might be integrated with various event systems.
122
123 DEBUGGING
124 By the time a "Future" object is destroyed, it ought to have been
125 completed or cancelled. By enabling debug tracing of objects, this fact
126 can be checked. If a future object is destroyed without having been
127 completed or cancelled, a warning message is printed.
128
129 $ PERL_FUTURE_DEBUG=1 perl -MFuture -E 'my $f = Future->new'
130 Future=HASH(0xaa61f8) was constructed at -e line 1 and was lost near -e line 0 before it was ready.
131
132 Note that due to a limitation of perl's "caller" function within a
133 "DESTROY" destructor method, the exact location of the leak cannot be
134 accurately determined. Often the leak will occur due to falling out of
135 scope by returning from a function; in this case the leak location may
136 be reported as being the line following the line calling that function.
137
138 $ PERL_FUTURE_DEBUG=1 perl -MFuture
139 sub foo {
140 my $f = Future->new;
141 }
142
143 foo();
144 print "Finished\n";
145
146 Future=HASH(0x14a2220) was constructed at - line 2 and was lost near - line 6 before it was ready.
147 Finished
148
149 A warning is also printed in debug mode if a "Future" object is
150 destroyed that completed with a failure, but the object believes that
151 failure has not been reported anywhere.
152
153 $ PERL_FUTURE_DEBUG=1 perl -Mblib -MFuture -E 'my $f = Future->fail("Oops")'
154 Future=HASH(0xac98f8) was constructed at -e line 1 and was lost near -e line 0 with an unreported failure of: Oops
155
156 Such a failure is considered reported if the "get" or "failure" methods
157 are called on it, or it had at least one "on_ready" or "on_fail"
158 callback, or its failure is propagated to another "Future" instance (by
159 a sequencing or converging method).
160
162 new
163 $future = Future->new
164
165 $future = $orig->new
166
167 Returns a new "Future" instance to represent a leaf future. It will be
168 marked as ready by any of the "done", "fail", or "cancel" methods. It
169 can be called either as a class method, or as an instance method.
170 Called on an instance it will construct another in the same class, and
171 is useful for subclassing.
172
173 This constructor would primarily be used by implementations of
174 asynchronous interfaces.
175
176 done (class method)
177 fail (class method)
178 $future = Future->done( @values )
179
180 $future = Future->fail( $exception, @details )
181
182 Since version 0.26.
183
184 Shortcut wrappers around creating a new "Future" then immediately
185 marking it as done or failed.
186
187 wrap
188 $future = Future->wrap( @values )
189
190 Since version 0.14.
191
192 If given a single argument which is already a "Future" reference, this
193 will be returned unmodified. Otherwise, returns a new "Future" instance
194 that is already complete, and will yield the given values.
195
196 This will ensure that an incoming argument is definitely a "Future",
197 and may be useful in such cases as adapting synchronous code to fit
198 asynchronous libraries driven by "Future".
199
200 call
201 $future = Future->call( \&code, @args )
202
203 Since version 0.15.
204
205 A convenient wrapper for calling a "CODE" reference that is expected to
206 return a future. In normal circumstances is equivalent to
207
208 $future = $code->( @args )
209
210 except that if the code throws an exception, it is wrapped in a new
211 immediate fail future. If the return value from the code is not a
212 blessed "Future" reference, an immediate fail future is returned
213 instead to complain about this fact.
214
216 As there are a lare number of methods on this class, they are
217 documented here in several sections.
218
220 The following methods query the internal state of a Future instance
221 without modifying it or otherwise causing side-effects.
222
223 is_ready
224 $ready = $future->is_ready
225
226 Returns true on a leaf future if a result has been provided to the
227 "done" method, failed using the "fail" method, or cancelled using the
228 "cancel" method.
229
230 Returns true on a convergent future if it is ready to yield a result,
231 depending on its component futures.
232
233 is_done
234 $done = $future->is_done
235
236 Returns true on a future if it is ready and completed successfully.
237 Returns false if it is still pending, failed, or was cancelled.
238
239 is_failed
240 $failed = $future->is_failed
241
242 Since version 0.26.
243
244 Returns true on a future if it is ready and it failed. Returns false if
245 it is still pending, completed successfully, or was cancelled.
246
247 is_cancelled
248 $cancelled = $future->is_cancelled
249
250 Returns true if the future has been cancelled by "cancel".
251
252 state
253 $str = $future->state
254
255 Since version 0.36.
256
257 Returns a string describing the state of the future, as one of the
258 three states named above; namely "done", "failed" or "cancelled", or
259 "pending" if it is none of these.
260
262 These methods would primarily be used by implementations of
263 asynchronous interfaces.
264
265 done
266 $future->done( @result )
267
268 Marks that the leaf future is now ready, and provides a list of values
269 as a result. (The empty list is allowed, and still indicates the future
270 as ready). Cannot be called on a convergent future.
271
272 If the future is already cancelled, this request is ignored. If the
273 future is already complete with a result or a failure, an exception is
274 thrown.
275
276 fail
277 $future->fail( $exception, @details )
278
279 Marks that the leaf future has failed, and provides an exception value.
280 This exception will be thrown by the "get" method if called.
281
282 The exception must evaluate as a true value; false exceptions are not
283 allowed. Further details may be provided that will be returned by the
284 "failure" method in list context. These details will not be part of the
285 exception string raised by "get".
286
287 If the future is already cancelled, this request is ignored. If the
288 future is already complete with a result or a failure, an exception is
289 thrown.
290
291 die
292 $future->die( $message, @details )
293
294 Since version 0.09.
295
296 A convenient wrapper around "fail". If the exception is a non-reference
297 that does not end in a linefeed, its value will be extended by the file
298 and line number of the caller, similar to the logic that "die" uses.
299
300 Returns the $future.
301
302 on_cancel
303 $future->on_cancel( $code )
304
305 If the future is not yet ready, adds a callback to be invoked if the
306 future is cancelled by the "cancel" method. If the future is already
307 ready the method is ignored.
308
309 If the future is later cancelled, the callbacks will be invoked in the
310 reverse order to that in which they were registered.
311
312 $on_cancel->( $future )
313
314 If passed another "Future" instance, the passed instance will be
315 cancelled when the original future is cancelled.
316
318 These methods would primarily be used by users of asynchronous
319 interfaces, on objects returned by such an interface.
320
321 on_ready
322 $future->on_ready( $code )
323
324 If the future is not yet ready, adds a callback to be invoked when the
325 future is ready. If the future is already ready, invokes it
326 immediately.
327
328 In either case, the callback will be passed the future object itself.
329 The invoked code can then obtain the list of results by calling the
330 "get" method.
331
332 $on_ready->( $future )
333
334 If passed another "Future" instance, the passed instance will have its
335 "done", "fail" or "cancel" methods invoked when the original future
336 completes successfully, fails, or is cancelled respectively.
337
338 Returns the $future.
339
340 get
341 @result = $future->get
342
343 $result = $future->get
344
345 If the future is ready and completed successfully, returns the list of
346 results that had earlier been given to the "done" method on a leaf
347 future, or the list of component futures it was waiting for on a
348 convergent future. In scalar context it returns just the first result
349 value.
350
351 If the future is ready but failed, this method raises as an exception
352 the failure string or object that was given to the "fail" method.
353
354 If the future was cancelled an exception is thrown.
355
356 If it is not yet ready and is not of a subclass that provides an
357 "await" method an exception is thrown. If it is subclassed to provide
358 an "await" method then this is used to wait for the future to be ready,
359 before returning the result or propagating its failure exception.
360
361 unwrap
362 @values = Future->unwrap( @values )
363
364 Since version 0.26.
365
366 If given a single argument which is a "Future" reference, this method
367 will call "get" on it and return the result. Otherwise, it returns the
368 list of values directly in list context, or the first value in scalar.
369 Since it involves an implicit "await", this method can only be used on
370 immediate futures or subclasses that implement "await".
371
372 This will ensure that an outgoing argument is definitely not a
373 "Future", and may be useful in such cases as adapting synchronous code
374 to fit asynchronous libraries that return "Future" instances.
375
376 on_done
377 $future->on_done( $code )
378
379 If the future is not yet ready, adds a callback to be invoked when the
380 future is ready, if it completes successfully. If the future completed
381 successfully, invokes it immediately. If it failed or was cancelled, it
382 is not invoked at all.
383
384 The callback will be passed the result passed to the "done" method.
385
386 $on_done->( @result )
387
388 If passed another "Future" instance, the passed instance will have its
389 "done" method invoked when the original future completes successfully.
390
391 Returns the $future.
392
393 failure
394 $exception = $future->failure
395
396 $exception, @details = $future->failure
397
398 If the future is ready, returns the exception passed to the "fail"
399 method or "undef" if the future completed successfully via the "done"
400 method.
401
402 If it is not yet ready and is not of a subclass that provides an
403 "await" method an exception is thrown. If it is subclassed to provide
404 an "await" method then this is used to wait for the future to be ready,
405 before returning the result or propagating its failure exception.
406
407 If called in list context, will additionally yield a list of the
408 details provided to the "fail" method.
409
410 Because the exception value must be true, this can be used in a simple
411 "if" statement:
412
413 if( my $exception = $future->failure ) {
414 ...
415 }
416 else {
417 my @result = $future->get;
418 ...
419 }
420
421 on_fail
422 $future->on_fail( $code )
423
424 If the future is not yet ready, adds a callback to be invoked when the
425 future is ready, if it fails. If the future has already failed, invokes
426 it immediately. If it completed successfully or was cancelled, it is
427 not invoked at all.
428
429 The callback will be passed the exception and details passed to the
430 "fail" method.
431
432 $on_fail->( $exception, @details )
433
434 If passed another "Future" instance, the passed instance will have its
435 "fail" method invoked when the original future fails.
436
437 To invoke a "done" method on a future when another one fails, use a
438 CODE reference:
439
440 $future->on_fail( sub { $f->done( @_ ) } );
441
442 Returns the $future.
443
444 cancel
445 $future->cancel
446
447 Requests that the future be cancelled, immediately marking it as ready.
448 This will invoke all of the code blocks registered by "on_cancel", in
449 the reverse order. When called on a convergent future, all its
450 component futures are also cancelled. It is not an error to attempt to
451 cancel a future that is already complete or cancelled; it simply has no
452 effect.
453
454 Returns the $future.
455
457 The following methods all return a new future to represent the
458 combination of its invocant followed by another action given by a code
459 reference. The combined activity waits for the first future to be
460 ready, then may invoke the code depending on the success or failure of
461 the first, or may run it regardless. The returned sequence future
462 represents the entire combination of activity.
463
464 In some cases the code should return a future; in some it should return
465 an immediate result. If a future is returned, the combined future will
466 then wait for the result of this second one. If the combinined future
467 is cancelled, it will cancel either the first future or the second,
468 depending whether the first had completed. If the code block throws an
469 exception instead of returning a value, the sequence future will fail
470 with that exception as its message and no further values.
471
472 As it is always a mistake to call these sequencing methods in void
473 context and lose the reference to the returned future (because
474 exception/error handling would be silently dropped), this method warns
475 in void context.
476
477 then
478 $future = $f1->then( \&done_code )
479
480 Since version 0.13.
481
482 Returns a new sequencing "Future" that runs the code if the first
483 succeeds. Once $f1 succeeds the code reference will be invoked and is
484 passed the list of results. It should return a future, $f2. Once $f2
485 completes the sequence future will then be marked as complete with
486 whatever result $f2 gave. If $f1 fails then the sequence future will
487 immediately fail with the same failure and the code will not be
488 invoked.
489
490 $f2 = $done_code->( @result )
491
492 else
493 $future = $f1->else( \&fail_code )
494
495 Since version 0.13.
496
497 Returns a new sequencing "Future" that runs the code if the first
498 fails. Once $f1 fails the code reference will be invoked and is passed
499 the failure and details. It should return a future, $f2. Once $f2
500 completes the sequence future will then be marked as complete with
501 whatever result $f2 gave. If $f1 succeeds then the sequence future will
502 immediately succeed with the same result and the code will not be
503 invoked.
504
505 $f2 = $fail_code->( $exception, @details )
506
507 then (2 arguments)
508 $future = $f1->then( \&done_code, \&fail_code )
509
510 The "then" method can also be passed the $fail_code block as well,
511 giving a combination of "then" and "else" behaviour.
512
513 This operation is designed to be compatible with the semantics of other
514 future systems, such as Javascript's Q or Promises/A libraries.
515
516 catch
517 $future = $f1->catch(
518 name => \&code,
519 name => \&code, ...
520 )
521
522 Since version 0.33.
523
524 Returns a new sequencing "Future" that behaves like an "else" call
525 which dispatches to a choice of several alternative handling functions
526 depending on the kind of failure that occurred. If $f1 fails with a
527 category name (i.e. the second argument to the "fail" call) which
528 exactly matches one of the string names given, then the corresponding
529 code is invoked, being passed the same arguments as a plain "else" call
530 would take, and is expected to return a "Future" in the same way.
531
532 $f2 = $code->( $exception, $name, @other_details )
533
534 If $f1 does not fail, fails without a category name at all, or fails
535 with a category name that does not match any given to the "catch"
536 method, then the returned sequence future immediately completes with
537 the same result, and no block of code is invoked.
538
539 If passed an odd-sized list, the final argument gives a function to
540 invoke on failure if no other handler matches.
541
542 $future = $f1->catch(
543 name => \&code, ...
544 \&fail_code,
545 )
546
547 This feature is currently still a work-in-progress. It currently can
548 only cope with category names that are literal strings, which are all
549 distinct. A later version may define other kinds of match (e.g.
550 regexp), may specify some sort of ordering on the arguments, or any of
551 several other semantic extensions. For more detail on the ongoing
552 design, see <https://rt.cpan.org/Ticket/Display.html?id=103545>.
553
554 then (multiple arguments)
555 $future = $f1->then( \&done_code, @catch_list, \&fail_code )
556
557 Since version 0.33.
558
559 The "then" method can be passed an even-sized list inbetween the
560 $done_code and the $fail_code, with the same meaning as the "catch"
561 method.
562
563 transform
564 $future = $f1->transform( %args )
565
566 Returns a new sequencing "Future" that wraps the one given as $f1. With
567 no arguments this will be a trivial wrapper; $future will complete or
568 fail when $f1 does, and $f1 will be cancelled when $future is.
569
570 By passing the following named arguments, the returned $future can be
571 made to behave differently to $f1:
572
573 done => CODE
574 Provides a function to use to modify the result of a successful
575 completion. When $f1 completes successfully, the result of its
576 "get" method is passed into this function, and whatever it
577 returns is passed to the "done" method of $future
578
579 fail => CODE
580 Provides a function to use to modify the result of a failure.
581 When $f1 fails, the result of its "failure" method is passed
582 into this function, and whatever it returns is passed to the
583 "fail" method of $future.
584
585 then_with_f
586 $future = $f1->then_with_f( ... )
587
588 Since version 0.21.
589
590 Returns a new sequencing "Future" that behaves like "then", but also
591 passes the original future, $f1, to any functions it invokes.
592
593 $f2 = $done_code->( $f1, @result )
594 $f2 = $catch_code->( $f1, $name, @other_details )
595 $f2 = $fail_code->( $f1, @details )
596
597 This is useful for conditional execution cases where the code block may
598 just return the same result of the original future. In this case it is
599 more efficient to return the original future itself.
600
601 then_done
602 then_fail
603 $future = $f->then_done( @result )
604
605 $future = $f->then_fail( $exception, @details )
606
607 Since version 0.22.
608
609 Convenient shortcuts to returning an immediate future from a "then"
610 block, when the result is already known.
611
612 else_with_f
613 $future = $f1->else_with_f( \&code )
614
615 Since version 0.21.
616
617 Returns a new sequencing "Future" that runs the code if the first
618 fails. Identical to "else", except that the code reference will be
619 passed both the original future, $f1, and its exception and details.
620
621 $f2 = $code->( $f1, $exception, @details )
622
623 This is useful for conditional execution cases where the code block may
624 just return the same result of the original future. In this case it is
625 more efficient to return the original future itself.
626
627 else_done
628 else_fail
629 $future = $f->else_done( @result )
630
631 $future = $f->else_fail( $exception, @details )
632
633 Since version 0.22.
634
635 Convenient shortcuts to returning an immediate future from a "else"
636 block, when the result is already known.
637
638 catch_with_f
639 $future = $f1->catch_with_f( ... )
640
641 Since version 0.33.
642
643 Returns a new sequencing "Future" that behaves like "catch", but also
644 passes the original future, $f1, to any functions it invokes.
645
646 followed_by
647 $future = $f1->followed_by( \&code )
648
649 Returns a new sequencing "Future" that runs the code regardless of
650 success or failure. Once $f1 is ready the code reference will be
651 invoked and is passed one argument, $f1. It should return a future,
652 $f2. Once $f2 completes the sequence future will then be marked as
653 complete with whatever result $f2 gave.
654
655 $f2 = $code->( $f1 )
656
657 without_cancel
658 $future = $f1->without_cancel
659
660 Since version 0.30.
661
662 Returns a new sequencing "Future" that will complete with the success
663 or failure of the original future, but if cancelled, will not cancel
664 the original. This may be useful if the original future represents an
665 operation that is being shared among multiple sequences; cancelling one
666 should not prevent the others from running too.
667
668 retain
669 $f = $f->retain
670
671 Since version 0.36.
672
673 Creates a reference cycle which causes the future to remain in memory
674 until it completes. Returns the invocant future.
675
676 In normal situations, a "Future" instance does not strongly hold a
677 reference to other futures that it is feeding a result into, instead
678 relying on that to be handled by application logic. This is normally
679 fine because some part of the application will retain the top-level
680 Future, which then strongly refers to each of its components down in a
681 tree. However, certain design patterns, such as mixed Future-based and
682 legacy callback-based API styles might end up creating Futures simply
683 to attach callback functions to them. In that situation, without
684 further attention, the Future may get lost due to having no strong
685 references to it. Calling "->retain" on it creates such a reference
686 which ensures it persists until it completes. For example:
687
688 Future->needs_all( $fA, $fB )
689 ->on_done( $on_done )
690 ->on_fail( $on_fail )
691 ->retain;
692
694 The following constructors all take a list of component futures, and
695 return a new future whose readiness somehow depends on the readiness of
696 those components. The first derived class component future will be used
697 as the prototype for constructing the return value, so it respects
698 subclassing correctly, or failing that a plain "Future".
699
700 wait_all
701 $future = Future->wait_all( @subfutures )
702
703 Returns a new "Future" instance that will indicate it is ready once all
704 of the sub future objects given to it indicate that they are ready,
705 either by success, failure or cancellation. Its result will be a list
706 of its component futures.
707
708 When given an empty list this constructor returns a new immediately-
709 done future.
710
711 This constructor would primarily be used by users of asynchronous
712 interfaces.
713
714 wait_any
715 $future = Future->wait_any( @subfutures )
716
717 Returns a new "Future" instance that will indicate it is ready once any
718 of the sub future objects given to it indicate that they are ready,
719 either by success or failure. Any remaining component futures that are
720 not yet ready will be cancelled. Its result will be the result of the
721 first component future that was ready; either success or failure. Any
722 component futures that are cancelled are ignored, apart from the final
723 component left; at which point the result will be a failure.
724
725 When given an empty list this constructor returns an immediately-failed
726 future.
727
728 This constructor would primarily be used by users of asynchronous
729 interfaces.
730
731 needs_all
732 $future = Future->needs_all( @subfutures )
733
734 Returns a new "Future" instance that will indicate it is ready once all
735 of the sub future objects given to it indicate that they have completed
736 successfully, or when any of them indicates that they have failed. If
737 any sub future fails, then this will fail immediately, and the
738 remaining subs not yet ready will be cancelled. Any component futures
739 that are cancelled will cause an immediate failure of the result.
740
741 If successful, its result will be a concatenated list of the results of
742 all its component futures, in corresponding order. If it fails, its
743 failure will be that of the first component future that failed. To
744 access each component future's results individually, use
745 "done_futures".
746
747 When given an empty list this constructor returns a new immediately-
748 done future.
749
750 This constructor would primarily be used by users of asynchronous
751 interfaces.
752
753 needs_any
754 $future = Future->needs_any( @subfutures )
755
756 Returns a new "Future" instance that will indicate it is ready once any
757 of the sub future objects given to it indicate that they have completed
758 successfully, or when all of them indicate that they have failed. If
759 any sub future succeeds, then this will succeed immediately, and the
760 remaining subs not yet ready will be cancelled. Any component futures
761 that are cancelled are ignored, apart from the final component left; at
762 which point the result will be a failure.
763
764 If successful, its result will be that of the first component future
765 that succeeded. If it fails, its failure will be that of the last
766 component future to fail. To access the other failures, use
767 "failed_futures".
768
769 Normally when this future completes successfully, only one of its
770 component futures will be done. If it is constructed with multiple that
771 are already done however, then all of these will be returned from
772 "done_futures". Users should be careful to still check all the results
773 from "done_futures" in that case.
774
775 When given an empty list this constructor returns an immediately-failed
776 future.
777
778 This constructor would primarily be used by users of asynchronous
779 interfaces.
780
782 The following methods apply to convergent (i.e. non-leaf) futures, to
783 access the component futures stored by it.
784
785 pending_futures
786 @f = $future->pending_futures
787
788 ready_futures
789 @f = $future->ready_futures
790
791 done_futures
792 @f = $future->done_futures
793
794 failed_futures
795 @f = $future->failed_futures
796
797 cancelled_futures
798 @f = $future->cancelled_futures
799
800 Return a list of all the pending, ready, done, failed, or cancelled
801 component futures. In scalar context, each will yield the number of
802 such component futures.
803
805 set_label
806 label
807 $future = $future->set_label( $label )
808
809 $label = $future->label
810
811 Since version 0.28.
812
813 Chaining mutator and accessor for the label of the "Future". This
814 should be a plain string value, whose value will be stored by the
815 future instance for use in debugging messages or other tooling, or
816 similar purposes.
817
818 btime
819 rtime
820 [ $sec, $usec ] = $future->btime
821
822 [ $sec, $usec ] = $future->rtime
823
824 Since version 0.28.
825
826 Accessors that return the tracing timestamps from the instance. These
827 give the time the instance was constructed ("birth" time, "btime") and
828 the time the result was determined (the "ready" time, "rtime"). Each
829 result is returned as a two-element ARRAY ref, containing the epoch
830 time in seconds and microseconds, as given by
831 "Time::HiRes::gettimeofday".
832
833 In order for these times to be captured, they have to be enabled by
834 setting $Future::TIMES to a true value. This is initialised true at the
835 time the module is loaded if either "PERL_FUTURE_DEBUG" or
836 "PERL_FUTURE_TIMES" are set in the environment.
837
838 elapsed
839 $sec = $future->elapsed
840
841 Since version 0.28.
842
843 If both tracing timestamps are defined, returns the number of seconds
844 of elapsed time between them as a floating-point number. If not,
845 returns "undef".
846
847 wrap_cb
848 $cb = $future->wrap_cb( $operation_name, $cb )
849
850 Since version 0.31.
851
852 Note: This method is experimental and may be changed or removed in a
853 later version.
854
855 This method is invoked internally by various methods that are about to
856 save a callback CODE reference supplied by the user, to be invoked
857 later. The default implementation simply returns the callback argument
858 as-is; the method is provided to allow users to provide extra
859 behaviour. This can be done by applying a method modifier of the
860 "around" kind, so in effect add a chain of wrappers. Each wrapper can
861 then perform its own wrapping logic of the callback. $operation_name is
862 a string giving the reason for which the callback is being saved;
863 currently one of "on_ready", "on_done", "on_fail" or "sequence"; the
864 latter being used for all the sequence-returning methods.
865
866 This method is intentionally invoked only for CODE references that are
867 being saved on a pending "Future" instance to be invoked at some later
868 point. It does not run for callbacks to be invoked on an already-
869 complete instance. This is for performance reasons, where the intended
870 behaviour is that the wrapper can provide some amount of context save
871 and restore, to return the operating environment for the callback back
872 to what it was at the time it was saved.
873
874 For example, the following wrapper saves the value of a package
875 variable at the time the callback was saved, and restores that value at
876 invocation time later on. This could be useful for preserving context
877 during logging in a Future-based program.
878
879 our $LOGGING_CTX;
880
881 no warnings 'redefine';
882
883 my $orig = Future->can( "wrap_cb" );
884 *Future::wrap_cb = sub {
885 my $cb = $orig->( @_ );
886
887 my $saved_logging_ctx = $LOGGING_CTX;
888
889 return sub {
890 local $LOGGING_CTX = $saved_logging_ctx;
891 $cb->( @_ );
892 };
893 };
894
895 At this point, any code deferred into a "Future" by any of its
896 callbacks will observe the $LOGGING_CTX variable as having the value it
897 held at the time the callback was saved, even if it is invoked later on
898 when that value is different.
899
900 Remember when writing such a wrapper, that it still needs to invoke the
901 previous version of the method, so that it plays nicely in combination
902 with others (see the "$orig->( @_ )" part).
903
905 The following examples all demonstrate possible uses of a "Future"
906 object to provide a fictional asynchronous API.
907
908 For more examples, comparing the use of "Future" with regular
909 call/return style Perl code, see also Future::Phrasebook.
910
911 Providing Results
912 By returning a new "Future" object each time the asynchronous function
913 is called, it provides a placeholder for its eventual result, and a way
914 to indicate when it is complete.
915
916 sub foperation
917 {
918 my %args = @_;
919
920 my $future = Future->new;
921
922 do_something_async(
923 foo => $args{foo},
924 on_done => sub { $future->done( @_ ); },
925 );
926
927 return $future;
928 }
929
930 In most cases, the "done" method will simply be invoked with the entire
931 result list as its arguments. In that case, it is convenient to use the
932 curry module to form a "CODE" reference that would invoke the "done"
933 method.
934
935 my $future = Future->new;
936
937 do_something_async(
938 foo => $args{foo},
939 on_done => $future->curry::done,
940 );
941
942 The caller may then use this future to wait for a result using the
943 "on_ready" method, and obtain the result using "get".
944
945 my $f = foperation( foo => "something" );
946
947 $f->on_ready( sub {
948 my $f = shift;
949 say "The operation returned: ", $f->get;
950 } );
951
952 Indicating Success or Failure
953 Because the stored exception value of a failed future may not be false,
954 the "failure" method can be used in a conditional statement to detect
955 success or failure.
956
957 my $f = foperation( foo => "something" );
958
959 $f->on_ready( sub {
960 my $f = shift;
961 if( not my $e = $f->failure ) {
962 say "The operation succeeded with: ", $f->get;
963 }
964 else {
965 say "The operation failed with: ", $e;
966 }
967 } );
968
969 By using "not" in the condition, the order of the "if" blocks can be
970 arranged to put the successful case first, similar to a "try"/"catch"
971 block.
972
973 Because the "get" method re-raises the passed exception if the future
974 failed, it can be used to control a "try"/"catch" block directly. (This
975 is sometimes called Exception Hoisting).
976
977 use Syntax::Keyword::Try;
978
979 $f->on_ready( sub {
980 my $f = shift;
981 try {
982 say "The operation succeeded with: ", $f->get;
983 }
984 catch {
985 say "The operation failed with: ", $_;
986 }
987 } );
988
989 Even neater still may be the separate use of the "on_done" and
990 "on_fail" methods.
991
992 $f->on_done( sub {
993 my @result = @_;
994 say "The operation succeeded with: ", @result;
995 } );
996 $f->on_fail( sub {
997 my ( $failure ) = @_;
998 say "The operation failed with: $failure";
999 } );
1000
1001 Immediate Futures
1002 Because the "done" method returns the future object itself, it can be
1003 used to generate a "Future" that is immediately ready with a result.
1004 This can also be used as a class method.
1005
1006 my $f = Future->done( $value );
1007
1008 Similarly, the "fail" and "die" methods can be used to generate a
1009 "Future" that is immediately failed.
1010
1011 my $f = Future->die( "This is never going to work" );
1012
1013 This could be considered similarly to a "die" call.
1014
1015 An "eval{}" block can be used to turn a "Future"-returning function
1016 that might throw an exception, into a "Future" that would indicate this
1017 failure.
1018
1019 my $f = eval { function() } || Future->fail( $@ );
1020
1021 This is neater handled by the "call" class method, which wraps the call
1022 in an "eval{}" block and tests the result:
1023
1024 my $f = Future->call( \&function );
1025
1026 Sequencing
1027 The "then" method can be used to create simple chains of dependent
1028 tasks, each one executing and returning a "Future" when the previous
1029 operation succeeds.
1030
1031 my $f = do_first()
1032 ->then( sub {
1033 return do_second();
1034 })
1035 ->then( sub {
1036 return do_third();
1037 });
1038
1039 The result of the $f future itself will be the result of the future
1040 returned by the final function, if none of them failed. If any of them
1041 fails it will fail with the same failure. This can be considered
1042 similar to normal exception handling in synchronous code; the first
1043 time a function call throws an exception, the subsequent calls are not
1044 made.
1045
1046 Merging Control Flow
1047 A "wait_all" future may be used to resynchronise control flow, while
1048 waiting for multiple concurrent operations to finish.
1049
1050 my $f1 = foperation( foo => "something" );
1051 my $f2 = foperation( bar => "something else" );
1052
1053 my $f = Future->wait_all( $f1, $f2 );
1054
1055 $f->on_ready( sub {
1056 say "Operations are ready:";
1057 say " foo: ", $f1->get;
1058 say " bar: ", $f2->get;
1059 } );
1060
1061 This provides an ability somewhat similar to "CPS::kpar()" or
1062 Async::MergePoint.
1063
1065 Cancellation of Non-Final Sequence Futures
1066 The behaviour of future cancellation still has some unanswered
1067 questions regarding how to handle the situation where a future is
1068 cancelled that has a sequence future constructed from it.
1069
1070 In particular, it is unclear in each of the following examples what the
1071 behaviour of $f2 should be, were $f1 to be cancelled:
1072
1073 $f2 = $f1->then( sub { ... } ); # plus related ->then_with_f, ...
1074
1075 $f2 = $f1->else( sub { ... } ); # plus related ->else_with_f, ...
1076
1077 $f2 = $f1->followed_by( sub { ... } );
1078
1079 In the "then"-style case it is likely that this situation should be
1080 treated as if $f1 had failed, perhaps with some special message. The
1081 "else"-style case is more complex, because it may be that the entire
1082 operation should still fail, or it may be that the cancellation of $f1
1083 should again be treated simply as a special kind of failure, and the
1084 "else" logic run as normal.
1085
1086 To be specific; in each case it is unclear what happens if the first
1087 future is cancelled, while the second one is still waiting on it. The
1088 semantics for "normal" top-down cancellation of $f2 and how it affects
1089 $f1 are already clear and defined.
1090
1091 Cancellation of Divergent Flow
1092 A further complication of cancellation comes from the case where a
1093 given future is reused multiple times for multiple sequences or
1094 convergent trees.
1095
1096 In particular, it is in clear in each of the following examples what
1097 the behaviour of $f2 should be, were $f1 to be cancelled:
1098
1099 my $f_initial = Future->new; ...
1100 my $f1 = $f_initial->then( ... );
1101 my $f2 = $f_initial->then( ... );
1102
1103 my $f1 = Future->needs_all( $f_initial );
1104 my $f2 = Future->needs_all( $f_initial );
1105
1106 The point of cancellation propagation is to trace backwards through
1107 stages of some larger sequence of operations that now no longer need to
1108 happen, because the final result is no longer required. But in each of
1109 these cases, just because $f1 has been cancelled, the initial future
1110 $f_initial is still required because there is another future ($f2) that
1111 will still require its result.
1112
1113 Initially it would appear that some kind of reference-counting
1114 mechanism could solve this question, though that itself is further
1115 complicated by the "on_ready" handler and its variants.
1116
1117 It may simply be that a comprehensive useful set of cancellation
1118 semantics can't be universally provided to cover all cases; and that
1119 some use-cases at least would require the application logic to give
1120 extra information to its "Future" objects on how they should wire up
1121 the cancel propagation logic.
1122
1123 Both of these cancellation issues are still under active design
1124 consideration; see the discussion on RT96685 for more information
1125 (<https://rt.cpan.org/Ticket/Display.html?id=96685>).
1126
1128 · Promises - an implementation of the "Promise/A+" pattern for
1129 asynchronous programming
1130
1131 · curry - Create automatic curried method call closures for any class
1132 or object
1133
1134 · "The Past, The Present and The Future" - slides from a talk given
1135 at the London Perl Workshop, 2012.
1136
1137 <https://docs.google.com/presentation/d/1UkV5oLcTOOXBXPh8foyxko4PR28_zU_aVx6gBms7uoo/edit>
1138
1139 · "Futures advent calendar 2013"
1140
1141 <http://leonerds-code.blogspot.co.uk/2013/12/futures-advent-day-1.html>
1142
1143 · "Asynchronous Programming with Futures" - YAPC::EU 2014
1144
1145 <https://www.youtube.com/watch?v=u9dZgFM6FtE>
1146
1148 · Consider the ability to pass the constructor an "await" CODEref,
1149 instead of needing to use a subclass. This might simplify
1150 async/etc.. implementations, and allows the reuse of the idea of
1151 subclassing to extend the abilities of "Future" itself - for
1152 example to allow a kind of Future that can report incremental
1153 progress.
1154
1156 Paul Evans <leonerd@leonerd.org.uk>
1157
1158
1159
1160perl v5.28.1 2019-02-02 Future(3)