NAME

Future - represent an operation awaiting completion

SYNOPSIS

my $future = Future->new;

perform_some_operation(
   on_complete => sub {
      $future->done( @_ );
   }
);

$future->on_ready( sub {
   say "The operation is complete";
} );

DESCRIPTION

A Future 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.

Some futures represent a single operation and are explicitly marked as ready by calling the done or fail methods. These are called "leaf" futures here, and are returned by the new constructor.

Other futures represent a collection sub-tasks, and are implicitly marked as ready depending on the readiness of their component futures as required. These are called "dependent" futures here, and are returned by the various wait_* and need_* constructors.

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.

See also Future::Utils which contains useful loop-constructing functions, to run a future-returning function repeatedly in a loop.

SUBCLASSING

This class easily supports being subclassed to provide extra behavior, such as giving the get method the ability to block and wait for completion. This may be useful to provide Future subclasses with event systems, or similar.

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 new method, and take context from the given instance.

sub new
{
   my $proto = shift;
   my $self = $proto->SUPER::new;

   if( ref $proto ) {
      # Prototype was an instance
   }
   else {
      # Prototype was a class
   }

   return $self;
}

If an instance provides a method called await, this will be called by the get and failure methods if the instance is pending.

$f->await

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 get call to the function or method calls.

my ( $results, $here ) = future_returning_function( @args )->get;

The examples directory in the distribution contains some examples of how futures might be integrated with various event systems.

MODULE DOCUMENTATION

Modules that provide future-returning functions or methods may wish to adopt the following styles in some way, to document the eventual return values from these futures.

func( ARGS, HERE... ) ==> ( RETURN, VALUES... )

OBJ->method( ARGS, HERE... ) ==> ( RETURN, VALUES... )

Code returning a future that yields no values on success can use empty parentheses.

func( ... ) ==> ()

DEBUGGING

By the time a Future 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.

This feature is enabled by setting an environment variable called PERL_FUTURE_DEBUG to some true value.

$ PERL_FUTURE_DEBUG=1 perl -MFuture -E 'my $f = Future->new'
Future=HASH(0xaa61f8) was constructed at -e line 1 and was lost near -e line 0 before it was ready.

Note that due to a limitation of perl's caller function within a DESTROY 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.

$ PERL_FUTURE_DEBUG=1 perl -MFuture
sub foo {
   my $f = Future->new;
}

foo();
print "Finished\n";

Future=HASH(0x14a2220) was constructed at - line 2 and was lost near - line 6 before it was ready.
Finished

CONSTRUCTORS

$future = Future->new

$future = $orig->new

Returns a new Future instance to represent a leaf future. It will be marked as ready by any of the done, fail, or cancel 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.

This constructor would primarily be used by implementations of asynchronous interfaces.

$future = Future->wrap( @values )

If given a single argument which is already a Future reference, this will be returned unmodified. Otherwise, returns a new Future instance that is already complete, and will yield the given values.

$future = Future->call( \&code, @args )

A convenient wrapper for calling a CODE reference that is expected to return a future. In normal circumstances is equivalent to

$future = $code->( @args )

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 Future reference, an immediate fail future is returned instead to complain about this fact.

IMPLEMENTATION METHODS

These methods would primarily be used by implementations of asynchronous interfaces.

$future->done( @result )

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 dependent future.

Returns the $future to allow easy chaining to create an immediate future by

return Future->new->done( ... )

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.

$code = $future->done_cb

Returns a CODE reference that, when invoked, calls the done method. This makes it simple to pass as a callback function to other code.

The same effect can be achieved using curry:

$code = $future->curry::done;

$future->fail( $exception, @details )

Marks that the leaf future has failed, and provides an exception value. This exception will be thrown by the get method if called.

The exception must evaluate as a true value; false exceptions are not allowed. Further details may be provided that will be returned by the failure method in list context. These details will not be part of the exception string raised by get.

Returns the $future to allow easy chaining to create an immediate failed future by

return Future->new->fail( ... )

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.

$code = $future->fail_cb

Returns a CODE reference that, when invoked, calls the fail method. This makes it simple to pass as a callback function to other code.

The same effect can be achieved using curry:

$code = $future->curry::fail;

$future->die( $message, @details )

A convenient wrapper around fail. 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 die uses.

Returns the $future.

$future->on_cancel( $code )

If the future is not yet ready, adds a callback to be invoked if the future is cancelled by the cancel method. If the future is already ready, throws an exception.

If the future is cancelled, the callbacks will be invoked in the reverse order to that in which they were registered.

$on_cancel->( $future )

$future->on_cancel( $f )

If passed another Future instance, the passed instance will be cancelled when the original future is cancelled. This method does nothing if the future is already complete.

$cancelled = $future->is_cancelled

Returns true if the future has been cancelled by cancel.

USER METHODS

These methods would primarily be used by users of asynchronous interfaces, on objects returned by such an interface.

$ready = $future->is_ready

Returns true on a leaf future if a result has been provided to the done method, failed using the fail method, or cancelled using the cancel method.

Returns true on a dependent future if it is ready to yield a result, depending on its component futures.

$future->on_ready( $code )

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.

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 get method.

$on_ready->( $future )

Returns the $future.

$future->on_ready( $f )

If passed another Future instance, the passed instance will have its done, fail or cancel methods invoked when the original future completes successfully, fails, or is cancelled respectively.

$done = $future->is_done

Returns true on a future if it is ready and completed successfully. Returns false if it is still pending, failed, or was cancelled.

@result = $future->get

$result = $future->get

If the future is ready and completed successfully, returns the list of results that had earlier been given to the done method on a leaf future, or the list of component futures it was waiting for on a dependent future. In scalar context it returns just the first result value.

If the future is ready but failed, this method raises as an exception the failure string or object that was given to the fail method.

If the future was cancelled an exception is thrown.

If it is not yet ready and is not of a subclass that provides an await method an exception is thrown. If it is subclassed to provide an await method then this is used to wait for the future to be ready, before returning the result or propagating its failure exception.

$future->on_done( $code )

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.

The callback will be passed the result passed to the done method.

$on_done->( @result )

Returns the $future.

$future->on_done( $f )

If passed another Future instance, the passed instance will have its done method invoked when the original future completes successfully.

$exception = $future->failure

$exception, @details = $future->failure

Returns the exception passed to the fail method, undef if the future completed successfully via the done method, or raises an exception if called on a future that is not yet ready.

If called in list context, will additionally yield a list of the details provided to the fail method.

Because the exception value must be true, this can be used in a simple if statement:

if( my $exception = $future->failure ) {
   ...
}
else {
   my @result = $future->get;
   ...
}

$future->on_fail( $code )

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.

The callback will be passed the exception and details passed to the fail method.

$on_fail->( $exception, @details )

Returns the $future.

$future->on_fail( $f )

If passed another Future instance, the passed instance will have its fail method invoked when the original future fails.

To invoke a done method on a future when another one fails, use a CODE reference:

$future->on_fail( sub { $f->done( @_ ) } );

$future->cancel

Requests that the future be cancelled, immediately marking it as ready. This will invoke all of the code blocks registered by on_cancel, in the reverse order. When called on a dependent 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.

Returns the $future.

$code = $future->cancel_cb

Returns a CODE reference that, when invoked, calls the cancel method. This makes it simple to pass as a callback function to other code.

The same effect can be achieved using curry:

$code = $future->curry::cancel;

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.

In some cases the code should return a future; in some it should return an immediate result. If a future is returned, 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.

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.

$future = $f1->then( \&done_code )

Returns a new sequencing Future that runs the code if the first succeeds. Once $f1 succeeds the code reference will be invoked and is passed the list of results. It should return a future, $f2. Once $f2 completes the sequence future will then be marked as complete with whatever result $f2 gave. If $f1 fails then the sequence future will immediately fail with the same failure and the code will not be invoked.

$f2 = $done_code->( @result )

$future = $f1->else( \&fail_code )

Returns a new sequencing Future that runs the code if the first fails. Once $f1 fails the code reference will be invoked and is passed the failure and details. It should return a future, $f2. Once $f2 completes the sequence future will then be marked as complete with whatever result $f2 gave. If $f1 succeeds then the sequence future will immediately succeed with the same result and the code will not be invoked.

$f2 = $fail_code->( $exception, @details )

$future = $f1->then( \&done_code, \&fail_code )

The then method can also be passed the $fail_code block as well, giving a combination of then and else behaviour.

This operation is designed to be compatible with the semantics of other future systems, such as Javascript's Q or Promises/A libraries.

$future = $f1->transform( %args )

Returns a new sequencing Future that wraps the one given as $f1. With no arguments this will be a trivial wrapper; $future will complete or fail when $f1 does, and $f1 will be cancelled when $future is.

By passing the following named arguments, the returned $future can be made to behave differently to $f1:

done => CODE

Provides a function to use to modify the result of a successful completion. When $f1 completes successfully, the result of its get method is passed into this function, and whatever it returns is passed to the done method of $future

fail => CODE

Provides a function to use to modify the result of a failure. When $f1 fails, the result of its failure method is passed into this function, and whatever it returns is passed to the fail method of $future.

$future = $f1->then_with_f( \&code )

Returns a new sequencing Future that runs the code if the first succeeds. Identical to then, except that the code reference will be passed both the original future, $f1, and its result.

$f2 = $code->( $f1, @result )

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.

$future = $f->then_done( @result )

$future = $f->then_fail( $exception, @details )

Convenient shortcuts to returning an immediate future from a then block, when the result is already known.

$future = $f1->else_with_f( \&code )

Returns a new sequencing Future that runs the code if the first fails. Identical to else, except that the code reference will be passed both the original future, $f1, and its exception and details.

$f2 = $code->( $f1, $exception, @details )

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.

$future = $f->else_done( @result )

$future = $f->else_fail( $exception, @details )

Convenient shortcuts to returning an immediate future from a else block, when the result is already known.

$future = $f1->followed_by( \&code )

Returns a new sequencing Future that runs the code regardless of success or failure. Once $f1 is ready the code reference will be invoked and is passed one argument, $f1. It should return a future, $f2. Once $f2 completes the sequence future will then be marked as complete with whatever result $f2 gave.

$f2 = $code->( $f1 )

$future = $f1->and_then( \&code )

An older form of then_with_f; this method passes only the original future itself to the code, not its result. The code would have to call get on the future to obtain the result.

$f2 = $code->( $f1 )

This method may be removed in a later version; use then_with_f in new code.

$future = $f1->or_else( \&code )

An older form of else_with_f; this method passes only the original future itself to the code, not its failure and details. The code would have to call failure on the future to obtain the result.

$f2 = $code->( $f1 )

This method may be removed in a later version; use else_with_f in new code.

DEPENDENT 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 Future.

$future = Future->wait_all( @subfutures )

Returns a new Future 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 or failure. Its result will a list of its component futures.

When given an empty list this constructor returns a new immediately-done future.

This constructor would primarily be used by users of asynchronous interfaces.

$future = Future->wait_any( @subfutures )

Returns a new Future 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.

When given an empty list this constructor returns an immediately-failed future.

This constructor would primarily be used by users of asynchronous interfaces.

$future = Future->needs_all( @subfutures )

Returns a new Future 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.

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 done_futures.

When given an empty list this constructor returns a new immediately-done future.

This constructor would primarily be used by users of asynchronous interfaces.

$future = Future->needs_any( @subfutures )

Returns a new Future 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.

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 failed_futures.

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 done_futures. Users should be careful to still check all the results from done_futures in that case.

When given an empty list this constructor returns an immediately-failed future.

This constructor would primarily be used by users of asynchronous interfaces.

METHODS ON DEPENDENT FUTURES

The following methods apply to dependent (i.e. non-leaf) futures, to access the component futures stored by it.

@f = $future->pending_futures

@f = $future->ready_futures

@f = $future->done_futures

@f = $future->failed_futures

@f = $future->cancelled_futures

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.

EXAMPLES

The following examples all demonstrate possible uses of a Future object to provide a fictional asynchronous API.

For more examples, comparing the use of Future with regular call/return style Perl code, see also Future::Phrasebook.

Providing Results

By returning a new Future 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.

sub foperation
{
   my %args = @_;

   my $future = Future->new;

   do_something_async(
      foo => $args{foo},
      on_done => sub { $future->done( @_ ); },
   );

   return $future;
}

In most cases, the done method will simply be invoked with the entire result list as its arguments. In that case, it is simpler to use the done_cb wrapper method to create the CODE reference.

my $future = Future->new;

do_something_async(
   foo => $args{foo},
   on_done => $future->done_cb,
);

The caller may then use this future to wait for a result using the on_ready method, and obtain the result using get.

my $f = foperation( foo => "something" );

$f->on_ready( sub {
   my $f = shift;
   say "The operation returned: ", $f->get;
} );

Indicating Success or Failure

Because the stored exception value of a failed future may not be false, the failure method can be used in a conditional statement to detect success or failure.

my $f = foperation( foo => "something" );

$f->on_ready( sub {
   my $f = shift;
   if( not my $e = $f->failure ) {
      say "The operation succeeded with: ", $f->get;
   }
   else {
      say "The operation failed with: ", $e;
   }
} );

By using not in the condition, the order of the if blocks can be arranged to put the successful case first, similar to a try/catch block.

Because the get method re-raises the passed exception if the future failed, it can be used to control a try/catch block directly. (This is sometimes called Exception Hoisting).

use Try::Tiny;

$f->on_ready( sub {
   my $f = shift;
   try {
      say "The operation succeeded with: ", $f->get;
   }
   catch {
      say "The operation failed with: ", $_;
   };
} );

Even neater still may be the separate use of the on_done and on_fail methods.

$f->on_done( sub {
   my @result = @_;
   say "The operation succeeded with: ", @result;
} );
$f->on_fail( sub {
   my ( $failure ) = @_;
   say "The operation failed with: $failure";
} );

Immediate Futures

Because the done method returns the future object itself, it can be used to generate a Future that is immediately ready with a result.

my $f = Future->new->done( $value );

This is neater handled by the wrap class method, which encapsulates its arguments in a new immediate Future, except if it is given a single argument that is already a Future:

my $f = Future->wrap( $value );

Similarly, the fail and die methods can be used to generate a Future that is immediately failed.

my $f = Future->new->die( "This is never going to work" );

This could be considered similarly to a die call.

An eval{} block can be used to turn a Future-returning function that might throw an exception, into a Future that would indicate this failure.

my $f = eval { function() } || Future->new->fail( $@ );

This is neater handled by the call class method, which wraps the call in an eval{} block and tests the result:

my $f = Future->call( \&function );

Sequencing

The then method can be used to create simple chains of dependent tasks, each one executing and returning a Future when the previous operation succeeds.

my $f = do_first()
           ->then( sub {
              return do_second();
           })
           ->then( sub {
              return do_third();
           });

The result of the $f 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.

Merging Control Flow

A wait_all future may be used to resynchronise control flow, while waiting for multiple concurrent operations to finish.

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->get;
   say "  bar: ", $f2->get;
} );

This provides an ability somewhat similar to CPS::kpar() or Async::MergePoint.

SEE ALSO

AUTHOR

Paul Evans <leonerd@leonerd.org.uk>