1 of 24

The Past, The Present and The Future

Paul Evans (PEVANS, LeoNerd)�$LOCATION

2 of 24

The Past

Straight line code

Synchronous

3 of 24

The Past

sub get_ball {

my ( $c ) = @_;

my $ball = slowly_get_ball($c);

return $ball;�}

my $red_ball = get_ball( "red" );

say $red_ball;

4 of 24

Asynchronous Callbacks

Pass in CODE reference

Function keeps it to call it later

Control flow goes backwards

5 of 24

Asynchronous Callbacks

sub get_ball_a {

my ( $c, $on_ball ) = @_;

...

}

my $on_ball = sub { say $_[0] };

get_ball_a( "red", $on_ball );

6 of 24

Futures

A proxy value

Represents an ongoing operation

7 of 24

Futures

sub get_ball_f {

my ( $c ) = @_;

return ## magic goes here ##�}

my $f = get_ball_f( "red" );

say $f->get;

8 of 24

cpan> Future

sub get_ball_f {

my ( $c ) = @_;

my $f = Future->new;

$f->done( Ball->new( $c ) );

return $f

}

9 of 24

cpan> Future

sub get_ball_f {

my ( $c ) = @_;

my $f = Future->new;

BallFetcher->fetch( $c,

sub { $f->done( @_ ) });

return $f

}

10 of 24

cpan> Future

my $f = get_ball_f( "red" );

$f->on_done(

sub {

my $ball = shift;

say $ball;

}

);

11 of 24

cpan> Future

Subclass or Proxy for more control

my $f = get_ball_f( "red" );

$f->await; ## implicit

my $ball = $f->get;

say $ball;

12 of 24

Success or Failure

Operations can succeed or fail

Futures can yield results or exceptions

13 of 24

Success or Failure

my $f = get_ball_f( "yellow" );

if( not $f->failure ) {

my $ball = $f->get;

}

else {

...

};

14 of 24

Success or Failure

my $f = get_ball_f( "yellow" );

try {

my $ball = $f->get;

}

catch {

...

};

15 of 24

Combining in Parallel

Want to do things concurrently

Combine many Futures to await them all

16 of 24

Combining in Parallel

my $f = Future->needs_all(

get_ball_f( "red" ),

get_ball_f( "green" ),

get_ball_f( "blue" )

);

my ($red, $green, $blue) = $f->get;

17 of 24

Combining in Sequence

A Future can trigger more code

... which can return another Future

18 of 24

Success or Failure

my $ball;

try {

$ball = get_ball_f( "yellow" )

->get; }

catch {

$ball = get_ball_f( "orange" )

->get; };

say $ball;

19 of 24

Success or Failure - better

my $f = get_ball_f( "yellow" );

my $g = $f->or_else( sub {

get_ball_f( "orange" )

});

say $g->get;

20 of 24

Success or Failure - better

my $f = get_ball_f( "yellow" )

->or_else( sub {

get_ball_f( "orange" )

});

say $f->get;

21 of 24

Cancelling

A Future is an operation in-progress

Operations can be cancelled

22 of 24

Cancelling

my $f = get_ball_f( "purple" );

sleep 20;

$f->is_ready or $f->cancel;

23 of 24

Cancelling Example: Timeouts

my $f = Future->wait_any(

get_ball_f( "purple" ),

timeout_f( 20 )

);

my $ball = $f->get;

24 of 24

Resources

cpan> install Future

LeoNerd @ irc.freenode.net, irc.perl.net

PEVANS on CPAN�