Futures advent day 2

Day 2 - Doing something when a Future completes

Because a Future object represents an operation that is currently in progress or has finished it provides the ideal place to attach logic to ask for further activity to happen when the original has completed. The most immediate way is to pass a piece of code in a sub reference to the on_done method.

my $f = GET("http://my-site-here.com/");

$f->on_done( sub {
  my ( $response ) = @_;
  print "Got a response\n";

In this case, as for many posts yet to come, we are presuming some hypothetical GET function that returns a Future wrapping an HTTP operation in the obvious manner.

If the returned Future is already complete (perhaps because it is a synchronous client that always completes immediately, or because it was served internally from a cache) then the on_done method invokes the code immediately. If not, the code is stored inside the Future object itself for when it eventually gets its result.

<< First | < Prev | Next >


  1. Are future's basically a promise object? (perhaps this'll be covered)

    1. Essentially, yes. The basic concept was independently created across a number of languages, and it turns out that two sets of terminology were created to name them.

      There tends to be a slight preference that functional languages prefer the word "Future", as compared imperative preferring "Promise". As such, the two styles sometimes have minor different semantics. Though that's only a convention, not a hard rule. C++ for example creates objects in pairs, in a way a little similar to a pipe() call, in that it has one object that the supplier will put the result into, and a different object that the consumer will read the result from. It calls these two the Future and the Promise.