2013/12/09

Futures advent day 9

Day 9 - The call and wrap methods

Over the past few days of code, a couple of common patterns have arisen. The first is that often a then or else block wishes to simply return a future immediately containing some results. Until now we have used the done method on a new future, which returns the future itself. Because this happens so often, a slightly neater (and internally more-efficient) form can be used instead, by using the wrap class method:

$f = Future->wrap( @values );

This is equivalent to constructing a new future and setting the values on it, except in the case that it was invoked with exactly one argument, and that argument was already a Future object. In that case, the future is returned directly.

Another pattern is that a block of code is called, and if it throws an exception it instead returns a future with that exception as its failure. The call class method takes a block of code and does this; returning either an immediately failed future if the code died, or returns the future that the code itself returned if it did not throw an exception.:

$f = Future->call( sub { ... } );
$f = Future->call( \&func, @arguments );

<< First | < Prev | Next >

No comments:

Post a Comment