.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.43) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "Future 3pm" .TH Future 3pm "2023-06-11" "perl v5.36.0" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" "Future" \- represent an operation awaiting completion .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& my $future = Future\->new; \& \& perform_some_operation( \& on_complete => sub { \& $future\->done( @_ ); \& } \& ); \& \& $future\->on_ready( sub { \& say "The operation is complete"; \& } ); .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" A \f(CW\*(C`Future\*(C'\fR object represents an operation that is currently in progress, or has recently completed. It can be used in a variety of ways to manage the flow of control, and data, through an asynchronous program. .PP Some futures represent a single operation and are explicitly marked as ready by calling the \f(CW\*(C`done\*(C'\fR or \f(CW\*(C`fail\*(C'\fR methods. These are called \*(L"leaf\*(R" futures here, and are returned by the \f(CW\*(C`new\*(C'\fR constructor. .PP Other futures represent a collection of sub-tasks, and are implicitly marked as ready depending on the readiness of their component futures as required. These are called \*(L"convergent\*(R" futures here as they converge control and data-flow back into one place. These are the ones returned by the various \&\f(CW\*(C`wait_*\*(C'\fR and \f(CW\*(C`need_*\*(C'\fR constructors. .PP It is intended that library functions that perform asynchronous operations would use future objects to represent outstanding operations, and allow their calling programs to control or wait for these operations to complete. The implementation and the user of such an interface would typically make use of different methods on the class. The methods below are documented in two sections; those of interest to each side of the interface. .PP It should be noted however, that this module does not in any way provide an actual mechanism for performing this asynchronous activity; it merely provides a way to create objects that can be used for control and data flow around those operations. It allows such code to be written in a neater, forward-reading manner, and simplifies many common patterns that are often involved in such situations. .PP See also Future::Utils which contains useful loop-constructing functions, to run a future-returning function repeatedly in a loop. .PP Unless otherwise noted, the following methods require at least version \&\fI0.08\fR. .SS "\s-1FAILURE CATEGORIES\s0" .IX Subsection "FAILURE CATEGORIES" While not directly required by \f(CW\*(C`Future\*(C'\fR or its related modules, a growing convention of \f(CW\*(C`Future\*(C'\fR\-using code is to encode extra semantics in the arguments given to the \f(CW\*(C`fail\*(C'\fR method, to represent different kinds of failure. .PP The convention is that after the initial message string as the first required argument (intended for display to humans), the second argument is a short lowercase string that relates in some way to the kind of failure that occurred. Following this is a list of details about that kind of failure, whose exact arrangement or structure are determined by the failure category. For example, IO::Async and Net::Async::HTTP use this convention to indicate at what stage a given \s-1HTTP\s0 request has failed: .PP .Vb 5 \& \->fail( $message, http => ... ) # an HTTP\-level error during protocol \& \->fail( $message, connect => ... ) # a TCP\-level failure to connect a \& # socket \& \->fail( $message, resolve => ... ) # a resolver (likely DNS) failure \& # to resolve a hostname .Ve .PP By following this convention, a module remains consistent with other \&\f(CW\*(C`Future\*(C'\fR\-based modules, and makes it easy for program logic to gracefully handle and manage failures by use of the \f(CW\*(C`catch\*(C'\fR method. .SS "\s-1SUBCLASSING\s0" .IX Subsection "SUBCLASSING" This class easily supports being subclassed to provide extra behavior, such as giving the \f(CW\*(C`get\*(C'\fR method the ability to block and wait for completion. This may be useful to provide \f(CW\*(C`Future\*(C'\fR subclasses with event systems, or similar. .PP Each method that returns a new future object will use the invocant to construct its return value. If the constructor needs to perform per-instance setup it can override the \f(CW\*(C`new\*(C'\fR method, and take context from the given instance. .PP .Vb 4 \& sub new \& { \& my $proto = shift; \& my $self = $proto\->SUPER::new; \& \& if( ref $proto ) { \& # Prototype was an instance \& } \& else { \& # Prototype was a class \& } \& \& return $self; \& } .Ve .PP If an instance overrides the \*(L"await\*(R" method, this will be called by \f(CW\*(C`get\*(C'\fR and \f(CW\*(C`failure\*(C'\fR if the instance is still pending. .PP In most cases this should allow future-returning modules to be used as if they were blocking call/return\-style modules, by simply appending a \f(CW\*(C`get\*(C'\fR call to the function or method calls. .PP .Vb 1 \& my ( $results, $here ) = future_returning_function( @args )\->get; .Ve .SS "\s-1DEBUGGING\s0" .IX Subsection "DEBUGGING" By the time a \f(CW\*(C`Future\*(C'\fR object is destroyed, it ought to have been completed or cancelled. By enabling debug tracing of objects, this fact can be checked. If a future object is destroyed without having been completed or cancelled, a warning message is printed. .PP .Vb 2 \& $ PERL_FUTURE_DEBUG=1 perl \-MFuture \-E \*(Aqmy $f = Future\->new\*(Aq \& Future=HASH(0xaa61f8) was constructed at \-e line 1 and was lost near \-e line 0 before it was ready. .Ve .PP Note that due to a limitation of perl's \f(CW\*(C`caller\*(C'\fR function within a \f(CW\*(C`DESTROY\*(C'\fR destructor method, the exact location of the leak cannot be accurately determined. Often the leak will occur due to falling out of scope by returning from a function; in this case the leak location may be reported as being the line following the line calling that function. .PP .Vb 4 \& $ PERL_FUTURE_DEBUG=1 perl \-MFuture \& sub foo { \& my $f = Future\->new; \& } \& \& foo(); \& print "Finished\en"; \& \& Future=HASH(0x14a2220) was constructed at \- line 2 and was lost near \- line 6 before it was ready. \& Finished .Ve .PP A warning is also printed in debug mode if a \f(CW\*(C`Future\*(C'\fR object is destroyed that completed with a failure, but the object believes that failure has not been reported anywhere. .PP .Vb 2 \& $ PERL_FUTURE_DEBUG=1 perl \-Mblib \-MFuture \-E \*(Aqmy $f = Future\->fail("Oops")\*(Aq \& Future=HASH(0xac98f8) was constructed at \-e line 1 and was lost near \-e line 0 with an unreported failure of: Oops .Ve .PP Such a failure is considered reported if the \f(CW\*(C`get\*(C'\fR or \f(CW\*(C`failure\*(C'\fR methods are called on it, or it had at least one \f(CW\*(C`on_ready\*(C'\fR or \f(CW\*(C`on_fail\*(C'\fR callback, or its failure is propagated to another \f(CW\*(C`Future\*(C'\fR instance (by a sequencing or converging method). .SS "Future::AsyncAwait::Awaitable \s-1ROLE\s0" .IX Subsection "Future::AsyncAwait::Awaitable ROLE" Since version 0.43 this module provides the Future::AsyncAwait::Awaitable \&\s-1API.\s0 Subclass authors should note that several of the \s-1API\s0 methods are provided by special optimised internal methods, which may require overriding in your subclass if your internals are different from that of this module. .SH "CONSTRUCTORS" .IX Header "CONSTRUCTORS" .SS "new" .IX Subsection "new" .Vb 1 \& $future = Future\->new \& \& $future = $orig\->new .Ve .PP Returns a new \f(CW\*(C`Future\*(C'\fR instance to represent a leaf future. It will be marked as ready by any of the \f(CW\*(C`done\*(C'\fR, \f(CW\*(C`fail\*(C'\fR, or \f(CW\*(C`cancel\*(C'\fR methods. It can be called either as a class method, or as an instance method. Called on an instance it will construct another in the same class, and is useful for subclassing. .PP This constructor would primarily be used by implementations of asynchronous interfaces. .SS "done \fI(class method)\fP" .IX Subsection "done (class method)" .SS "fail \fI(class method)\fP" .IX Subsection "fail (class method)" .Vb 1 \& $future = Future\->done( @values ) \& \& $future = Future\->fail( $exception, $category, @details ) .Ve .PP \&\fISince version 0.26.\fR .PP Shortcut wrappers around creating a new \f(CW\*(C`Future\*(C'\fR then immediately marking it as done or failed. .SS "wrap" .IX Subsection "wrap" .Vb 1 \& $future = Future\->wrap( @values ) .Ve .PP \&\fISince version 0.14.\fR .PP If given a single argument which is already a \f(CW\*(C`Future\*(C'\fR reference, this will be returned unmodified. Otherwise, returns a new \f(CW\*(C`Future\*(C'\fR instance that is already complete, and will yield the given values. .PP This will ensure that an incoming argument is definitely a \f(CW\*(C`Future\*(C'\fR, and may be useful in such cases as adapting synchronous code to fit asynchronous libraries driven by \f(CW\*(C`Future\*(C'\fR. .SS "call" .IX Subsection "call" .Vb 1 \& $future = Future\->call( \e&code, @args ) .Ve .PP \&\fISince version 0.15.\fR .PP A convenient wrapper for calling a \f(CW\*(C`CODE\*(C'\fR reference that is expected to return a future. In normal circumstances is equivalent to .PP .Vb 1 \& $future = $code\->( @args ) .Ve .PP except that if the code throws an exception, it is wrapped in a new immediate fail future. If the return value from the code is not a blessed \f(CW\*(C`Future\*(C'\fR reference, an immediate fail future is returned instead to complain about this fact. .SH "METHODS" .IX Header "METHODS" As there are a lare number of methods on this class, they are documented here in several sections. .SH "INSPECTION METHODS" .IX Header "INSPECTION METHODS" The following methods query the internal state of a Future instance without modifying it or otherwise causing side-effects. .SS "is_ready" .IX Subsection "is_ready" .Vb 1 \& $ready = $future\->is_ready .Ve .PP Returns true on a leaf future if a result has been provided to the \f(CW\*(C`done\*(C'\fR method, failed using the \f(CW\*(C`fail\*(C'\fR method, or cancelled using the \f(CW\*(C`cancel\*(C'\fR method. .PP Returns true on a convergent future if it is ready to yield a result, depending on its component futures. .SS "is_done" .IX Subsection "is_done" .Vb 1 \& $done = $future\->is_done .Ve .PP Returns true on a future if it is ready and completed successfully. Returns false if it is still pending, failed, or was cancelled. .SS "is_failed" .IX Subsection "is_failed" .Vb 1 \& $failed = $future\->is_failed .Ve .PP \&\fISince version 0.26.\fR .PP Returns true on a future if it is ready and it failed. Returns false if it is still pending, completed successfully, or was cancelled. .SS "is_cancelled" .IX Subsection "is_cancelled" .Vb 1 \& $cancelled = $future\->is_cancelled .Ve .PP Returns true if the future has been cancelled by \f(CW\*(C`cancel\*(C'\fR. .SS "state" .IX Subsection "state" .Vb 1 \& $str = $future\->state .Ve .PP \&\fISince version 0.36.\fR .PP Returns a string describing the state of the future, as one of the three states named above; namely \f(CW\*(C`done\*(C'\fR, \f(CW\*(C`failed\*(C'\fR or \f(CW\*(C`cancelled\*(C'\fR, or \f(CW\*(C`pending\*(C'\fR if it is none of these. .SH "IMPLEMENTATION METHODS" .IX Header "IMPLEMENTATION METHODS" These methods would primarily be used by implementations of asynchronous interfaces. .SS "done" .IX Subsection "done" .Vb 1 \& $future\->done( @result ) .Ve .PP Marks that the leaf future is now ready, and provides a list of values as a result. (The empty list is allowed, and still indicates the future as ready). Cannot be called on a convergent future. .PP If the future is already cancelled, this request is ignored. If the future is already complete with a result or a failure, an exception is thrown. .PP \&\fISince version 0.45:\fR this method is also available under the name \&\f(CW\*(C`resolve\*(C'\fR. .SS "fail" .IX Subsection "fail" .Vb 1 \& $future\->fail( $exception, $category, @details ) .Ve .PP Marks that the leaf future has failed, and provides an exception value. This exception will be thrown by the \f(CW\*(C`get\*(C'\fR method if called. .PP The exception must evaluate as a true value; false exceptions are not allowed. A failure category name and other further details may be provided that will be returned by the \f(CW\*(C`failure\*(C'\fR method in list context. .PP If the future is already cancelled, this request is ignored. If the future is already complete with a result or a failure, an exception is thrown. .PP If passed a Future::Exception instance (i.e. an object previously thrown by the \f(CW\*(C`get\*(C'\fR), the additional details will be preserved. This allows the additional details to be transparently preserved by such code as .PP .Vb 4 \& ... \& catch { \& return Future\->fail($@); \& } .Ve .PP \&\fISince version 0.45:\fR this method is also available under the name \f(CW\*(C`reject\*(C'\fR. .SS "die" .IX Subsection "die" .Vb 1 \& $future\->die( $message, $category, @details ) .Ve .PP \&\fISince version 0.09.\fR .PP A convenient wrapper around \f(CW\*(C`fail\*(C'\fR. If the exception is a non-reference that does not end in a linefeed, its value will be extended by the file and line number of the caller, similar to the logic that \f(CW\*(C`die\*(C'\fR uses. .PP Returns the \f(CW$future\fR. .SS "on_cancel" .IX Subsection "on_cancel" .Vb 1 \& $future\->on_cancel( $code ) .Ve .PP If the future is not yet ready, adds a callback to be invoked if the future is cancelled by the \f(CW\*(C`cancel\*(C'\fR method. If the future is already ready the method is ignored. .PP If the future is later cancelled, the callbacks will be invoked in the reverse order to that in which they were registered. .PP .Vb 1 \& $on_cancel\->( $future ) .Ve .PP If passed another \f(CW\*(C`Future\*(C'\fR instance, the passed instance will be cancelled when the original future is cancelled. In this case, the reference is only strongly held while the target future remains pending. If it becomes ready, then there is no point trying to cancel it, and so it is removed from the originating future's cancellation list. .SH "USER METHODS" .IX Header "USER METHODS" These methods would primarily be used by users of asynchronous interfaces, on objects returned by such an interface. .SS "on_ready" .IX Subsection "on_ready" .Vb 1 \& $future\->on_ready( $code ) .Ve .PP If the future is not yet ready, adds a callback to be invoked when the future is ready. If the future is already ready, invokes it immediately. .PP In either case, the callback will be passed the future object itself. The invoked code can then obtain the list of results by calling the \f(CW\*(C`get\*(C'\fR method. .PP .Vb 1 \& $on_ready\->( $future ) .Ve .PP If passed another \f(CW\*(C`Future\*(C'\fR instance, the passed instance will have its \&\f(CW\*(C`done\*(C'\fR, \f(CW\*(C`fail\*(C'\fR or \f(CW\*(C`cancel\*(C'\fR methods invoked when the original future completes successfully, fails, or is cancelled respectively. .PP Returns the \f(CW$future\fR. .SS "result" .IX Subsection "result" .Vb 1 \& @result = $future\->result \& \& $result = $future\->result .Ve .PP \&\fISince version 0.44.\fR .PP If the future is ready and completed successfully, returns the list of results that had earlier been given to the \f(CW\*(C`done\*(C'\fR method on a leaf future, or the list of component futures it was waiting for on a convergent future. In scalar context it returns just the first result value. .PP If the future is ready but failed, this method raises as an exception the failure that was given to the \f(CW\*(C`fail\*(C'\fR method. If additional details were given to the \f(CW\*(C`fail\*(C'\fR method, an exception object is constructed to wrap them of type Future::Exception. .PP If the future was cancelled or is not yet ready an exception is thrown. .SS "get" .IX Subsection "get" .Vb 1 \& @result = $future\->get \& \& $result = $future\->get .Ve .PP If the future is ready, returns the result or throws the failure exception as per \*(L"result\*(R". .PP If it is not yet ready then \*(L"await\*(R" is invoked to wait for a ready state, and the result returned as above. .SS "await" .IX Subsection "await" .Vb 1 \& $f = $f\->await .Ve .PP \&\fISince version 0.44.\fR .PP Blocks until the future instance is no longer pending. .PP Returns the invocant future itself, so it is useful for chaining. .PP Usually, calling code would either force the future using \*(L"get\*(R", or use either \f(CW\*(C`then\*(C'\fR chaining or \f(CW\*(C`async/await\*(C'\fR syntax to wait for results. This method is useful in cases where the exception-throwing part of \f(CW\*(C`get\*(C'\fR is not required, perhaps because other code will be testing the result using \&\*(L"is_done\*(R" or similar. .PP .Vb 3 \& if( $f\->await\->is_done ) { \& ... \& } .Ve .PP This method is intended for subclasses to override. The default implementation will throw an exception if called on a still-pending instance. .SS "block_until_ready" .IX Subsection "block_until_ready" .Vb 1 \& $f = $f\->block_until_ready .Ve .PP \&\fISince version 0.40.\fR .PP Now a synonym for \*(L"await\*(R". New code should invoke \f(CW\*(C`await\*(C'\fR directly. .SS "unwrap" .IX Subsection "unwrap" .Vb 1 \& @values = Future\->unwrap( @values ) .Ve .PP \&\fISince version 0.26.\fR .PP If given a single argument which is a \f(CW\*(C`Future\*(C'\fR reference, this method will call \f(CW\*(C`get\*(C'\fR on it and return the result. Otherwise, it returns the list of values directly in list context, or the first value in scalar. Since it involves an implicit blocking wait, this method can only be used on immediate futures or subclasses that implement \*(L"await\*(R". .PP This will ensure that an outgoing argument is definitely not a \f(CW\*(C`Future\*(C'\fR, and may be useful in such cases as adapting synchronous code to fit asynchronous libraries that return \f(CW\*(C`Future\*(C'\fR instances. .SS "on_done" .IX Subsection "on_done" .Vb 1 \& $future\->on_done( $code ) .Ve .PP If the future is not yet ready, adds a callback to be invoked when the future is ready, if it completes successfully. If the future completed successfully, invokes it immediately. If it failed or was cancelled, it is not invoked at all. .PP The callback will be passed the result passed to the \f(CW\*(C`done\*(C'\fR method. .PP .Vb 1 \& $on_done\->( @result ) .Ve .PP If passed another \f(CW\*(C`Future\*(C'\fR instance, the passed instance will have its \&\f(CW\*(C`done\*(C'\fR method invoked when the original future completes successfully. .PP Returns the \f(CW$future\fR. .SS "failure" .IX Subsection "failure" .Vb 1 \& $exception = $future\->failure \& \& $exception, $category, @details = $future\->failure .Ve .PP If the future is ready, returns the exception passed to the \f(CW\*(C`fail\*(C'\fR method or \&\f(CW\*(C`undef\*(C'\fR if the future completed successfully via the \f(CW\*(C`done\*(C'\fR method. .PP If it is not yet ready then \*(L"await\*(R" is invoked to wait for a ready state. .PP If called in list context, will additionally yield the category name and list of the details provided to the \f(CW\*(C`fail\*(C'\fR method. .PP Because the exception value must be true, this can be used in a simple \f(CW\*(C`if\*(C'\fR statement: .PP .Vb 7 \& if( my $exception = $future\->failure ) { \& ... \& } \& else { \& my @result = $future\->result; \& ... \& } .Ve .SS "on_fail" .IX Subsection "on_fail" .Vb 1 \& $future\->on_fail( $code ) .Ve .PP If the future is not yet ready, adds a callback to be invoked when the future is ready, if it fails. If the future has already failed, invokes it immediately. If it completed successfully or was cancelled, it is not invoked at all. .PP The callback will be passed the exception and other details passed to the \&\f(CW\*(C`fail\*(C'\fR method. .PP .Vb 1 \& $on_fail\->( $exception, $category, @details ) .Ve .PP If passed another \f(CW\*(C`Future\*(C'\fR instance, the passed instance will have its \&\f(CW\*(C`fail\*(C'\fR method invoked when the original future fails. .PP To invoke a \f(CW\*(C`done\*(C'\fR method on a future when another one fails, use a \s-1CODE\s0 reference: .PP .Vb 1 \& $future\->on_fail( sub { $f\->done( @_ ) } ); .Ve .PP Returns the \f(CW$future\fR. .SS "cancel" .IX Subsection "cancel" .Vb 1 \& $future\->cancel .Ve .PP Requests that the future be cancelled, immediately marking it as ready. This will invoke all of the code blocks registered by \f(CW\*(C`on_cancel\*(C'\fR, in the reverse order. When called on a convergent future, all its component futures are also cancelled. It is not an error to attempt to cancel a future that is already complete or cancelled; it simply has no effect. .PP Returns the \f(CW$future\fR. .SH "SEQUENCING METHODS" .IX Header "SEQUENCING METHODS" The following methods all return a new future to represent the combination of its invocant followed by another action given by a code reference. The combined activity waits for the first future to be ready, then may invoke the code depending on the success or failure of the first, or may run it regardless. The returned sequence future represents the entire combination of activity. .PP The invoked code could return a future, or a result directly. .PP \&\fISince version 0.45:\fR if a non-future result is returned it will be wrapped in a new immediate Future instance. This behaviour can be disabled by setting the \f(CW\*(C`PERL_FUTURE_STRICT\*(C'\fR environment variable to a true value at compiletime: .PP .Vb 1 \& $ PERL_FUTURE_STRICT=1 perl ... .Ve .PP The combined future will then wait for the result of this second one. If the combinined future is cancelled, it will cancel either the first future or the second, depending whether the first had completed. If the code block throws an exception instead of returning a value, the sequence future will fail with that exception as its message and no further values. .PP Note that since the code is invoked in scalar context, you cannot directly return a list of values this way. Any list-valued results must be done by returning a \f(CW\*(C`Future\*(C'\fR instance. .PP .Vb 4 \& sub { \& ... \& return Future\->done( @results ); \& } .Ve .PP As it is always a mistake to call these sequencing methods in void context and lose the reference to the returned future (because exception/error handling would be silently dropped), this method warns in void context. .SS "then" .IX Subsection "then" .Vb 1 \& $future = $f1\->then( \e&done_code ) .Ve .PP \&\fISince version 0.13.\fR .PP Returns a new sequencing \f(CW\*(C`Future\*(C'\fR that runs the code if the first succeeds. Once \f(CW$f1\fR succeeds the code reference will be invoked and is passed the list of results. It should return a future, \f(CW$f2\fR. Once \f(CW$f2\fR completes the sequence future will then be marked as complete with whatever result \f(CW$f2\fR gave. If \f(CW$f1\fR fails then the sequence future will immediately fail with the same failure and the code will not be invoked. .PP .Vb 1 \& $f2 = $done_code\->( @result ) .Ve .SS "else" .IX Subsection "else" .Vb 1 \& $future = $f1\->else( \e&fail_code ) .Ve .PP \&\fISince version 0.13.\fR .PP Returns a new sequencing \f(CW\*(C`Future\*(C'\fR that runs the code if the first fails. Once \&\f(CW$f1\fR fails the code reference will be invoked and is passed the failure and other details. It should return a future, \f(CW$f2\fR. Once \f(CW$f2\fR completes the sequence future will then be marked as complete with whatever result \f(CW$f2\fR gave. If \f(CW$f1\fR succeeds then the sequence future will immediately succeed with the same result and the code will not be invoked. .PP .Vb 1 \& $f2 = $fail_code\->( $exception, $category, @details ) .Ve .SS "then \fI(2 arguments)\fP" .IX Subsection "then (2 arguments)" .Vb 1 \& $future = $f1\->then( \e&done_code, \e&fail_code ) .Ve .PP The \f(CW\*(C`then\*(C'\fR method can also be passed the \f(CW$fail_code\fR block as well, giving a combination of \f(CW\*(C`then\*(C'\fR and \f(CW\*(C`else\*(C'\fR behaviour. .PP This operation is similar to those provided by other future systems, such as Javascript's Q or Promises/A libraries. .SS "catch" .IX Subsection "catch" .Vb 4 \& $future = $f1\->catch( \& name => \e&code, \& name => \e&code, ... \& ) .Ve .PP \&\fISince version 0.33.\fR .PP Returns a new sequencing \f(CW\*(C`Future\*(C'\fR that behaves like an \f(CW\*(C`else\*(C'\fR call which dispatches to a choice of several alternative handling functions depending on the kind of failure that occurred. If \f(CW$f1\fR fails with a category name (i.e. the second argument to the \f(CW\*(C`fail\*(C'\fR call) which exactly matches one of the string names given, then the corresponding code is invoked, being passed the same arguments as a plain \f(CW\*(C`else\*(C'\fR call would take, and is expected to return a \&\f(CW\*(C`Future\*(C'\fR in the same way. .PP .Vb 1 \& $f2 = $code\->( $exception, $category, @details ) .Ve .PP If \f(CW$f1\fR does not fail, fails without a category name at all, or fails with a category name that does not match any given to the \f(CW\*(C`catch\*(C'\fR method, then the returned sequence future immediately completes with the same result, and no block of code is invoked. .PP If passed an odd-sized list, the final argument gives a function to invoke on failure if no other handler matches. .PP .Vb 4 \& $future = $f1\->catch( \& name => \e&code, ... \& \e&fail_code, \& ) .Ve .PP This feature is currently still a work-in-progress. It currently can only cope with category names that are literal strings, which are all distinct. A later version may define other kinds of match (e.g. regexp), may specify some sort of ordering on the arguments, or any of several other semantic extensions. For more detail on the ongoing design, see . .SS "then \fI(multiple arguments)\fP" .IX Subsection "then (multiple arguments)" .Vb 1 \& $future = $f1\->then( \e&done_code, @catch_list, \e&fail_code ) .Ve .PP \&\fISince version 0.33.\fR .PP The \f(CW\*(C`then\*(C'\fR method can be passed an even-sized list inbetween the \&\f(CW$done_code\fR and the \f(CW$fail_code\fR, with the same meaning as the \f(CW\*(C`catch\*(C'\fR method. .SS "transform" .IX Subsection "transform" .Vb 1 \& $future = $f1\->transform( %args ) .Ve .PP Returns a new sequencing \f(CW\*(C`Future\*(C'\fR that wraps the one given as \f(CW$f1\fR. With no arguments this will be a trivial wrapper; \f(CW$future\fR will complete or fail when \f(CW$f1\fR does, and \f(CW$f1\fR will be cancelled when \f(CW$future\fR is. .PP By passing the following named arguments, the returned \f(CW$future\fR can be made to behave differently to \f(CW$f1\fR: .IP "done => \s-1CODE\s0" 8 .IX Item "done => CODE" Provides a function to use to modify the result of a successful completion. When \f(CW$f1\fR completes successfully, the result of its \f(CW\*(C`get\*(C'\fR method is passed into this function, and whatever it returns is passed to the \f(CW\*(C`done\*(C'\fR method of \&\f(CW$future\fR .IP "fail => \s-1CODE\s0" 8 .IX Item "fail => CODE" Provides a function to use to modify the result of a failure. When \f(CW$f1\fR fails, the result of its \f(CW\*(C`failure\*(C'\fR method is passed into this function, and whatever it returns is passed to the \f(CW\*(C`fail\*(C'\fR method of \f(CW$future\fR. .SS "then_with_f" .IX Subsection "then_with_f" .Vb 1 \& $future = $f1\->then_with_f( ... ) .Ve .PP \&\fISince version 0.21.\fR .PP Returns a new sequencing \f(CW\*(C`Future\*(C'\fR that behaves like \f(CW\*(C`then\*(C'\fR, but also passes the original future, \f(CW$f1\fR, to any functions it invokes. .PP .Vb 3 \& $f2 = $done_code\->( $f1, @result ) \& $f2 = $catch_code\->( $f1, $category, @details ) \& $f2 = $fail_code\->( $f1, $category, @details ) .Ve .PP This is useful for conditional execution cases where the code block may just return the same result of the original future. In this case it is more efficient to return the original future itself. .SS "then_done" .IX Subsection "then_done" .SS "then_fail" .IX Subsection "then_fail" .Vb 1 \& $future = $f\->then_done( @result ) \& \& $future = $f\->then_fail( $exception, $category, @details ) .Ve .PP \&\fISince version 0.22.\fR .PP Convenient shortcuts to returning an immediate future from a \f(CW\*(C`then\*(C'\fR block, when the result is already known. .SS "else_with_f" .IX Subsection "else_with_f" .Vb 1 \& $future = $f1\->else_with_f( \e&code ) .Ve .PP \&\fISince version 0.21.\fR .PP Returns a new sequencing \f(CW\*(C`Future\*(C'\fR that runs the code if the first fails. Identical to \f(CW\*(C`else\*(C'\fR, except that the code reference will be passed both the original future, \f(CW$f1\fR, and its exception and other details. .PP .Vb 1 \& $f2 = $code\->( $f1, $exception, $category, @details ) .Ve .PP This is useful for conditional execution cases where the code block may just return the same result of the original future. In this case it is more efficient to return the original future itself. .SS "else_done" .IX Subsection "else_done" .SS "else_fail" .IX Subsection "else_fail" .Vb 1 \& $future = $f\->else_done( @result ) \& \& $future = $f\->else_fail( $exception, $category, @details ) .Ve .PP \&\fISince version 0.22.\fR .PP Convenient shortcuts to returning an immediate future from a \f(CW\*(C`else\*(C'\fR block, when the result is already known. .SS "catch_with_f" .IX Subsection "catch_with_f" .Vb 1 \& $future = $f1\->catch_with_f( ... ) .Ve .PP \&\fISince version 0.33.\fR .PP Returns a new sequencing \f(CW\*(C`Future\*(C'\fR that behaves like \f(CW\*(C`catch\*(C'\fR, but also passes the original future, \f(CW$f1\fR, to any functions it invokes. .SS "followed_by" .IX Subsection "followed_by" .Vb 1 \& $future = $f1\->followed_by( \e&code ) .Ve .PP Returns a new sequencing \f(CW\*(C`Future\*(C'\fR that runs the code regardless of success or failure. Once \f(CW$f1\fR is ready the code reference will be invoked and is passed one argument, \f(CW$f1\fR. It should return a future, \f(CW$f2\fR. Once \f(CW$f2\fR completes the sequence future will then be marked as complete with whatever result \&\f(CW$f2\fR gave. .PP .Vb 1 \& $f2 = $code\->( $f1 ) .Ve .SS "without_cancel" .IX Subsection "without_cancel" .Vb 1 \& $future = $f1\->without_cancel .Ve .PP \&\fISince version 0.30.\fR .PP Returns a new sequencing \f(CW\*(C`Future\*(C'\fR that will complete with the success or failure of the original future, but if cancelled, will not cancel the original. This may be useful if the original future represents an operation that is being shared among multiple sequences; cancelling one should not prevent the others from running too. .PP Note that this only prevents cancel propagating from \f(CW$future\fR to \f(CW$f1\fR; if the original \f(CW$f1\fR instance is cancelled then the returned \f(CW$future\fR will have to be cancelled too. .SS "retain" .IX Subsection "retain" .Vb 1 \& $f = $f\->retain .Ve .PP \&\fISince version 0.36.\fR .PP Creates a reference cycle which causes the future to remain in memory until it completes. Returns the invocant future. .PP In normal situations, a \f(CW\*(C`Future\*(C'\fR instance does not strongly hold a reference to other futures that it is feeding a result into, instead relying on that to be handled by application logic. This is normally fine because some part of the application will retain the top-level Future, which then strongly refers to each of its components down in a tree. However, certain design patterns, such as mixed Future-based and legacy callback-based \s-1API\s0 styles might end up creating Futures simply to attach callback functions to them. In that situation, without further attention, the Future may get lost due to having no strong references to it. Calling \f(CW\*(C`\->retain\*(C'\fR on it creates such a reference which ensures it persists until it completes. For example: .PP .Vb 4 \& Future\->needs_all( $fA, $fB ) \& \->on_done( $on_done ) \& \->on_fail( $on_fail ) \& \->retain; .Ve .SH "CONVERGENT FUTURES" .IX Header "CONVERGENT FUTURES" The following constructors all take a list of component futures, and return a new future whose readiness somehow depends on the readiness of those components. The first derived class component future will be used as the prototype for constructing the return value, so it respects subclassing correctly, or failing that a plain \f(CW\*(C`Future\*(C'\fR. .SS "wait_all" .IX Subsection "wait_all" .Vb 1 \& $future = Future\->wait_all( @subfutures ) .Ve .PP Returns a new \f(CW\*(C`Future\*(C'\fR instance that will indicate it is ready once all of the sub future objects given to it indicate that they are ready, either by success, failure or cancellation. Its result will be a list of its component futures. .PP When given an empty list this constructor returns a new immediately-done future. .PP This constructor would primarily be used by users of asynchronous interfaces. .SS "wait_any" .IX Subsection "wait_any" .Vb 1 \& $future = Future\->wait_any( @subfutures ) .Ve .PP Returns a new \f(CW\*(C`Future\*(C'\fR instance that will indicate it is ready once any of the sub future objects given to it indicate that they are ready, either by success or failure. Any remaining component futures that are not yet ready will be cancelled. Its result will be the result of the first component future that was ready; either success or failure. Any component futures that are cancelled are ignored, apart from the final component left; at which point the result will be a failure. .PP When given an empty list this constructor returns an immediately-failed future. .PP This constructor would primarily be used by users of asynchronous interfaces. .SS "needs_all" .IX Subsection "needs_all" .Vb 1 \& $future = Future\->needs_all( @subfutures ) .Ve .PP Returns a new \f(CW\*(C`Future\*(C'\fR instance that will indicate it is ready once all of the sub future objects given to it indicate that they have completed successfully, or when any of them indicates that they have failed. If any sub future fails, then this will fail immediately, and the remaining subs not yet ready will be cancelled. Any component futures that are cancelled will cause an immediate failure of the result. .PP If successful, its result will be a concatenated list of the results of all its component futures, in corresponding order. If it fails, its failure will be that of the first component future that failed. To access each component future's results individually, use \f(CW\*(C`done_futures\*(C'\fR. .PP When given an empty list this constructor returns a new immediately-done future. .PP This constructor would primarily be used by users of asynchronous interfaces. .SS "needs_any" .IX Subsection "needs_any" .Vb 1 \& $future = Future\->needs_any( @subfutures ) .Ve .PP Returns a new \f(CW\*(C`Future\*(C'\fR instance that will indicate it is ready once any of the sub future objects given to it indicate that they have completed successfully, or when all of them indicate that they have failed. If any sub future succeeds, then this will succeed immediately, and the remaining subs not yet ready will be cancelled. Any component futures that are cancelled are ignored, apart from the final component left; at which point the result will be a failure. .PP If successful, its result will be that of the first component future that succeeded. If it fails, its failure will be that of the last component future to fail. To access the other failures, use \f(CW\*(C`failed_futures\*(C'\fR. .PP Normally when this future completes successfully, only one of its component futures will be done. If it is constructed with multiple that are already done however, then all of these will be returned from \f(CW\*(C`done_futures\*(C'\fR. Users should be careful to still check all the results from \f(CW\*(C`done_futures\*(C'\fR in that case. .PP When given an empty list this constructor returns an immediately-failed future. .PP This constructor would primarily be used by users of asynchronous interfaces. .SH "METHODS ON CONVERGENT FUTURES" .IX Header "METHODS ON CONVERGENT FUTURES" The following methods apply to convergent (i.e. non-leaf) futures, to access the component futures stored by it. .SS "pending_futures" .IX Subsection "pending_futures" .Vb 1 \& @f = $future\->pending_futures .Ve .SS "ready_futures" .IX Subsection "ready_futures" .Vb 1 \& @f = $future\->ready_futures .Ve .SS "done_futures" .IX Subsection "done_futures" .Vb 1 \& @f = $future\->done_futures .Ve .SS "failed_futures" .IX Subsection "failed_futures" .Vb 1 \& @f = $future\->failed_futures .Ve .SS "cancelled_futures" .IX Subsection "cancelled_futures" .Vb 1 \& @f = $future\->cancelled_futures .Ve .PP Return a list of all the pending, ready, done, failed, or cancelled component futures. In scalar context, each will yield the number of such component futures. .SH "SUBCLASSING METHODS" .IX Header "SUBCLASSING METHODS" These methods are not intended for end-users of \f(CW\*(C`Future\*(C'\fR instances, but instead provided for authors of classes that subclass from \f(CW\*(C`Future\*(C'\fR itself. .SS "set_udata" .IX Subsection "set_udata" .Vb 1 \& $future = $future\->set_udata( $name, $value ) .Ve .PP \&\fISince version 0.49\fR .PP Stores a Perl value within the instance, under the given name. Subclasses can use this to store extra data that the implementation may require. .PP This is a safer version of attempting to use the \f(CW$future\fR instance itself as a hash reference. .SS "udata" .IX Subsection "udata" .Vb 1 \& $value = $future\->udata( $name ) .Ve .PP \&\fISince version 0.49\fR .PP Returns a Perl value from the instance that was previously set with \&\*(L"set_udata\*(R". .SH "TRACING METHODS" .IX Header "TRACING METHODS" .SS "set_label" .IX Subsection "set_label" .SS "label" .IX Subsection "label" .Vb 1 \& $future = $future\->set_label( $label ) \& \& $label = $future\->label .Ve .PP \&\fISince version 0.28.\fR .PP Chaining mutator and accessor for the label of the \f(CW\*(C`Future\*(C'\fR. This should be a plain string value, whose value will be stored by the future instance for use in debugging messages or other tooling, or similar purposes. .SS "btime" .IX Subsection "btime" .SS "rtime" .IX Subsection "rtime" .Vb 1 \& [ $sec, $usec ] = $future\->btime \& \& [ $sec, $usec ] = $future\->rtime .Ve .PP \&\fISince version 0.28.\fR .PP Accessors that return the tracing timestamps from the instance. These give the time the instance was constructed (\*(L"birth\*(R" time, \f(CW\*(C`btime\*(C'\fR) and the time the result was determined (the \*(L"ready\*(R" time, \f(CW\*(C`rtime\*(C'\fR). Each result is returned as a two-element \s-1ARRAY\s0 ref, containing the epoch time in seconds and microseconds, as given by \f(CW\*(C`Time::HiRes::gettimeofday\*(C'\fR. .PP In order for these times to be captured, they have to be enabled by setting \&\f(CW$Future::TIMES\fR to a true value. This is initialised true at the time the module is loaded if either \f(CW\*(C`PERL_FUTURE_DEBUG\*(C'\fR or \f(CW\*(C`PERL_FUTURE_TIMES\*(C'\fR are set in the environment. .SS "elapsed" .IX Subsection "elapsed" .Vb 1 \& $sec = $future\->elapsed .Ve .PP \&\fISince version 0.28.\fR .PP If both tracing timestamps are defined, returns the number of seconds of elapsed time between them as a floating-point number. If not, returns \&\f(CW\*(C`undef\*(C'\fR. .SS "wrap_cb" .IX Subsection "wrap_cb" .Vb 1 \& $cb = $future\->wrap_cb( $operation_name, $cb ) .Ve .PP \&\fISince version 0.31.\fR .PP \&\fINote: This method is experimental and may be changed or removed in a later version.\fR .PP This method is invoked internally by various methods that are about to save a callback \s-1CODE\s0 reference supplied by the user, to be invoked later. The default implementation simply returns the callback argument as-is; the method is provided to allow users to provide extra behaviour. This can be done by applying a method modifier of the \f(CW\*(C`around\*(C'\fR kind, so in effect add a chain of wrappers. Each wrapper can then perform its own wrapping logic of the callback. \f(CW$operation_name\fR is a string giving the reason for which the callback is being saved; currently one of \f(CW\*(C`on_ready\*(C'\fR, \f(CW\*(C`on_done\*(C'\fR, \f(CW\*(C`on_fail\*(C'\fR or \f(CW\*(C`sequence\*(C'\fR; the latter being used for all the sequence-returning methods. .PP This method is intentionally invoked only for \s-1CODE\s0 references that are being saved on a pending \f(CW\*(C`Future\*(C'\fR instance to be invoked at some later point. It does not run for callbacks to be invoked on an already-complete instance. This is for performance reasons, where the intended behaviour is that the wrapper can provide some amount of context save and restore, to return the operating environment for the callback back to what it was at the time it was saved. .PP For example, the following wrapper saves the value of a package variable at the time the callback was saved, and restores that value at invocation time later on. This could be useful for preserving context during logging in a Future-based program. .PP .Vb 1 \& our $LOGGING_CTX; \& \& no warnings \*(Aqredefine\*(Aq; \& \& my $orig = Future\->can( "wrap_cb" ); \& *Future::wrap_cb = sub { \& my $cb = $orig\->( @_ ); \& \& my $saved_logging_ctx = $LOGGING_CTX; \& \& return sub { \& local $LOGGING_CTX = $saved_logging_ctx; \& $cb\->( @_ ); \& }; \& }; .Ve .PP At this point, any code deferred into a \f(CW\*(C`Future\*(C'\fR by any of its callbacks will observe the \f(CW$LOGGING_CTX\fR variable as having the value it held at the time the callback was saved, even if it is invoked later on when that value is different. .PP Remember when writing such a wrapper, that it still needs to invoke the previous version of the method, so that it plays nicely in combination with others (see the \f(CW\*(C`$orig\->( @_ )\*(C'\fR part). .SH "EXAMPLES" .IX Header "EXAMPLES" The following examples all demonstrate possible uses of a \f(CW\*(C`Future\*(C'\fR object to provide a fictional asynchronous \s-1API.\s0 .PP For more examples, comparing the use of \f(CW\*(C`Future\*(C'\fR with regular call/return style Perl code, see also Future::Phrasebook. .SS "Providing Results" .IX Subsection "Providing Results" By returning a new \f(CW\*(C`Future\*(C'\fR object each time the asynchronous function is called, it provides a placeholder for its eventual result, and a way to indicate when it is complete. .PP .Vb 3 \& sub foperation \& { \& my %args = @_; \& \& my $future = Future\->new; \& \& do_something_async( \& foo => $args{foo}, \& on_done => sub { $future\->done( @_ ); }, \& ); \& \& return $future; \& } .Ve .PP In most cases, the \f(CW\*(C`done\*(C'\fR method will simply be invoked with the entire result list as its arguments. In that case, it is convenient to use the curry module to form a \f(CW\*(C`CODE\*(C'\fR reference that would invoke the \f(CW\*(C`done\*(C'\fR method. .PP .Vb 1 \& my $future = Future\->new; \& \& do_something_async( \& foo => $args{foo}, \& on_done => $future\->curry::done, \& ); .Ve .PP The caller may then use this future to wait for a result using the \f(CW\*(C`on_ready\*(C'\fR method, and obtain the result using \f(CW\*(C`get\*(C'\fR. .PP .Vb 1 \& my $f = foperation( foo => "something" ); \& \& $f\->on_ready( sub { \& my $f = shift; \& say "The operation returned: ", $f\->result; \& } ); .Ve .SS "Indicating Success or Failure" .IX Subsection "Indicating Success or Failure" Because the stored exception value of a failed future may not be false, the \&\f(CW\*(C`failure\*(C'\fR method can be used in a conditional statement to detect success or failure. .PP .Vb 1 \& my $f = foperation( foo => "something" ); \& \& $f\->on_ready( sub { \& my $f = shift; \& if( not my $e = $f\->failure ) { \& say "The operation succeeded with: ", $f\->result; \& } \& else { \& say "The operation failed with: ", $e; \& } \& } ); .Ve .PP By using \f(CW\*(C`not\*(C'\fR in the condition, the order of the \f(CW\*(C`if\*(C'\fR blocks can be arranged to put the successful case first, similar to a \f(CW\*(C`try\*(C'\fR/\f(CW\*(C`catch\*(C'\fR block. .PP Because the \f(CW\*(C`get\*(C'\fR method re-raises the passed exception if the future failed, it can be used to control a \f(CW\*(C`try\*(C'\fR/\f(CW\*(C`catch\*(C'\fR block directly. (This is sometimes called \fIException Hoisting\fR). .PP .Vb 1 \& use Syntax::Keyword::Try; \& \& $f\->on_ready( sub { \& my $f = shift; \& try { \& say "The operation succeeded with: ", $f\->result; \& } \& catch { \& say "The operation failed with: ", $_; \& } \& } ); .Ve .PP Even neater still may be the separate use of the \f(CW\*(C`on_done\*(C'\fR and \f(CW\*(C`on_fail\*(C'\fR methods. .PP .Vb 8 \& $f\->on_done( sub { \& my @result = @_; \& say "The operation succeeded with: ", @result; \& } ); \& $f\->on_fail( sub { \& my ( $failure ) = @_; \& say "The operation failed with: $failure"; \& } ); .Ve .SS "Immediate Futures" .IX Subsection "Immediate Futures" Because the \f(CW\*(C`done\*(C'\fR method returns the future object itself, it can be used to generate a \f(CW\*(C`Future\*(C'\fR that is immediately ready with a result. This can also be used as a class method. .PP .Vb 1 \& my $f = Future\->done( $value ); .Ve .PP Similarly, the \f(CW\*(C`fail\*(C'\fR and \f(CW\*(C`die\*(C'\fR methods can be used to generate a \f(CW\*(C`Future\*(C'\fR that is immediately failed. .PP .Vb 1 \& my $f = Future\->die( "This is never going to work" ); .Ve .PP This could be considered similarly to a \f(CW\*(C`die\*(C'\fR call. .PP An \f(CW\*(C`eval{}\*(C'\fR block can be used to turn a \f(CW\*(C`Future\*(C'\fR\-returning function that might throw an exception, into a \f(CW\*(C`Future\*(C'\fR that would indicate this failure. .PP .Vb 1 \& my $f = eval { function() } || Future\->fail( $@ ); .Ve .PP This is neater handled by the \f(CW\*(C`call\*(C'\fR class method, which wraps the call in an \f(CW\*(C`eval{}\*(C'\fR block and tests the result: .PP .Vb 1 \& my $f = Future\->call( \e&function ); .Ve .SS "Sequencing" .IX Subsection "Sequencing" The \f(CW\*(C`then\*(C'\fR method can be used to create simple chains of dependent tasks, each one executing and returning a \f(CW\*(C`Future\*(C'\fR when the previous operation succeeds. .PP .Vb 7 \& my $f = do_first() \& \->then( sub { \& return do_second(); \& }) \& \->then( sub { \& return do_third(); \& }); .Ve .PP The result of the \f(CW$f\fR future itself will be the result of the future returned by the final function, if none of them failed. If any of them fails it will fail with the same failure. This can be considered similar to normal exception handling in synchronous code; the first time a function call throws an exception, the subsequent calls are not made. .SS "Merging Control Flow" .IX Subsection "Merging Control Flow" A \f(CW\*(C`wait_all\*(C'\fR future may be used to resynchronise control flow, while waiting for multiple concurrent operations to finish. .PP .Vb 2 \& my $f1 = foperation( foo => "something" ); \& my $f2 = foperation( bar => "something else" ); \& \& my $f = Future\->wait_all( $f1, $f2 ); \& \& $f\->on_ready( sub { \& say "Operations are ready:"; \& say " foo: ", $f1\->result; \& say " bar: ", $f2\->result; \& } ); .Ve .PP This provides an ability somewhat similar to \f(CW\*(C`CPS::kpar()\*(C'\fR or Async::MergePoint. .SH "KNOWN ISSUES" .IX Header "KNOWN ISSUES" .SS "Cancellation of Non-Final Sequence Futures" .IX Subsection "Cancellation of Non-Final Sequence Futures" The behaviour of future cancellation still has some unanswered questions regarding how to handle the situation where a future is cancelled that has a sequence future constructed from it. .PP In particular, it is unclear in each of the following examples what the behaviour of \f(CW$f2\fR should be, were \f(CW$f1\fR to be cancelled: .PP .Vb 1 \& $f2 = $f1\->then( sub { ... } ); # plus related \->then_with_f, ... \& \& $f2 = $f1\->else( sub { ... } ); # plus related \->else_with_f, ... \& \& $f2 = $f1\->followed_by( sub { ... } ); .Ve .PP In the \f(CW\*(C`then\*(C'\fR\-style case it is likely that this situation should be treated as if \f(CW$f1\fR had failed, perhaps with some special message. The \f(CW\*(C`else\*(C'\fR\-style case is more complex, because it may be that the entire operation should still fail, or it may be that the cancellation of \f(CW$f1\fR should again be treated simply as a special kind of failure, and the \f(CW\*(C`else\*(C'\fR logic run as normal. .PP To be specific; in each case it is unclear what happens if the first future is cancelled, while the second one is still waiting on it. The semantics for \&\*(L"normal\*(R" top-down cancellation of \f(CW$f2\fR and how it affects \f(CW$f1\fR are already clear and defined. .SS "Cancellation of Divergent Flow" .IX Subsection "Cancellation of Divergent Flow" A further complication of cancellation comes from the case where a given future is reused multiple times for multiple sequences or convergent trees. .PP In particular, it is in clear in each of the following examples what the behaviour of \f(CW$f2\fR should be, were \f(CW$f1\fR to be cancelled: .PP .Vb 3 \& my $f_initial = Future\->new; ... \& my $f1 = $f_initial\->then( ... ); \& my $f2 = $f_initial\->then( ... ); \& \& my $f1 = Future\->needs_all( $f_initial ); \& my $f2 = Future\->needs_all( $f_initial ); .Ve .PP The point of cancellation propagation is to trace backwards through stages of some larger sequence of operations that now no longer need to happen, because the final result is no longer required. But in each of these cases, just because \f(CW$f1\fR has been cancelled, the initial future \f(CW$f_initial\fR is still required because there is another future (\f(CW$f2\fR) that will still require its result. .PP Initially it would appear that some kind of reference-counting mechanism could solve this question, though that itself is further complicated by the \&\f(CW\*(C`on_ready\*(C'\fR handler and its variants. .PP It may simply be that a comprehensive useful set of cancellation semantics can't be universally provided to cover all cases; and that some use-cases at least would require the application logic to give extra information to its \&\f(CW\*(C`Future\*(C'\fR objects on how they should wire up the cancel propagation logic. .PP Both of these cancellation issues are still under active design consideration; see the discussion on \s-1RT96685\s0 for more information (). .SH "SEE ALSO" .IX Header "SEE ALSO" .IP "\(bu" 4 Future::AsyncAwait \- deferred subroutine syntax for futures .Sp Provides a neat syntax extension for writing future-based code. .IP "\(bu" 4 Future::IO \- Future-returning \s-1IO\s0 methods .Sp Provides methods similar to core \s-1IO\s0 functions, which yield results by Futures. .IP "\(bu" 4 Promises \- an implementation of the \*(L"Promise/A+\*(R" pattern for asynchronous programming .Sp A different alternative implementation of a similar idea. .IP "\(bu" 4 curry \- Create automatic curried method call closures for any class or object .IP "\(bu" 4 \&\*(L"The Past, The Present and The Future\*(R" \- slides from a talk given at the London Perl Workshop, 2012. .Sp .IP "\(bu" 4 \&\*(L"Futures advent calendar 2013\*(R" .Sp .IP "\(bu" 4 \&\*(L"Asynchronous Programming with Futures\*(R" \- \s-1YAPC::EU 2014\s0 .Sp .SH "TODO" .IX Header "TODO" .IP "\(bu" 4 Consider the ability to pass the constructor a \f(CW\*(C`block\*(C'\fR CODEref, instead of needing to use a subclass. This might simplify async/etc.. implementations, and allows the reuse of the idea of subclassing to extend the abilities of \&\f(CW\*(C`Future\*(C'\fR itself \- for example to allow a kind of Future that can report incremental progress. .SH "AUTHOR" .IX Header "AUTHOR" Paul Evans