2013/12/11

Futures advent day 11

Day 11 - Transforming Results or Failures

While we are on the subject of convenient shortcuts to neaten up certain kinds of Future result handling, another common pattern that arises is the case of an immediate return; either a then block that returns an immediate result based on the given values, or an else block that returns an immediate failure based on the given one. In each of these cases the transform method allows us to write this more conveniently.

sub GET_title
{
  my ( $url ) = @_;

  GET_checked($url)->transform(
    done => sub { get_page_title( $_[0] ) },
  );
}

If the GET_title is successful then the code passed in the done argument is invoked with the result as the argument list, and whatever it returns is used as the result of the future that transform returned. This is a little shorter and more convenient than the functionally-equivalent then block returning an immediate future.

We can similarly use transform on the failure message to create a different message, perhaps with more details in it.

sub GET_title
{
  my ( $url ) = @_;

  GET_checked($url)->transform(
    done => sub {
      get_page_title( $_[0] )
    },
    fail => sub {
      my $message = shift;
      "Cannot get title of $url - $message", @_;
    }
  );
}

Because the failure may contain other values giving more context, we need to be careful to preserve them. This is done most easily by shifting the message, so the remaining values appear in @_.

<< First | < Prev | Next >

No comments:

Post a Comment

Post a Comment