2013/12/03

Futures advent day 3

Day 3 - Chaining Futures to perform a sequence of actions

A more powerful ability than on_done, and one which in practice turns out to be used much more often, is provided by the then method. This method itself returns a Future, and expects code that will return a Future when it is invoked. In this way it provides an ability to perform a second action which returns a Future after the first one completes, and returns a Future that represents the complete combination of the first and the second.

my $f = GET("http://my-site-here.com/first")
  ->then( sub {
    my ( $first_response ) = @_;
    my $path = path_from_response($first_response);
    GET("http://my-site-here.com/$path);
  });

my $second_response = $f->get;

In this second example after the first page has been returned we then fetch a second page by somehow using the result of the first page's response to give a path name for the second. The returned Future in $f will be complete after this second response has been received. The call to get will then wait for this to happen.

Of course, we are not limited to simply two actions - because the then method returns another Future, we can simply call then on that as well to chain as many steps of a process as are necessary to complete it. This leads to a neat sequence of code, quite unlike the ever-indenting nature of passing callback functions.

<< First | < Prev | Next >

No comments:

Post a Comment