Futures advent day 4

Day 4 - Coping with failure

So far every Future example we have seen has resulted in an eventual success. But, like regular perl functions can either return a result or die() an exception, so too can Futures either complete with a result or a failure. Whereas the on_done method attaches code to handle a successful result we can use on_fail similarly to attach code to handle a failure.

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

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

$f->on_fail( sub {
  my ( $failure ) = @_;
  print STDERR "It failed: $failure\n";

If the get method receives a failure on the Future instead of a success, it throws the message from that failure as a perl exception, causing the method to die instead of return. This leads to many cases of Future code being able to look and act very similarly to regular perl function calls, with values being returned, or exceptions being thrown and caught.

<< First | < Prev | Next >

No comments:

Post a Comment