await_all shouldn't short circuit on an exception
[scpubgit/Object-Remote.git] / lib / Object / Remote / Future.pm
CommitLineData
dc28afe8 1package Object::Remote::Future;
2
3use strict;
4use warnings;
5use base qw(Exporter);
6
7use CPS::Future;
8
3f1f1e66 9our @EXPORT = qw(future await_future await_all);
dc28afe8 10
11sub future (&) {
12 my $f = $_[0]->(CPS::Future->new);
13 return $f if ((caller(1)||'') eq 'start');
14 await_future($f);
15}
16
17sub await_future {
18 my $f = shift;
19 return $f if $f->is_ready;
20 require Object::Remote;
21 my $loop = Object::Remote->current_loop;
22 $f->on_ready(sub { $loop->stop });
23 $loop->run;
24 return wantarray ? $f->get : ($f->get)[0];
25}
26
3f1f1e66 27sub await_all {
f6888810 28 await_future(CPS::Future->wait_all(@_));
3f1f1e66 29 map $_->get, @_;
30}
31
dc28afe8 32package start;
33
34sub AUTOLOAD {
35 my $invocant = shift;
8ba4f2e3 36 my ($method) = our $AUTOLOAD =~ /^start::(.+)$/;
dc28afe8 37 my $res;
38 unless (eval { $res = $invocant->$method(@_); 1 }) {
39 my $f = CPS::Future->new;
40 $f->fail($@);
41 return $f;
42 }
43 unless (Scalar::Util::blessed($res) and $res->isa('CPS::Future')) {
44 my $f = CPS::Future->new;
45 $f->done($res);
46 return $f;
47 }
48 return $res;
49}
50
9822fc76 51package maybe::start;
52
53sub AUTOLOAD {
54 my $invocant = shift;
55 my ($method) = our $AUTOLOAD =~ /^maybe::start::(.+)$/;
56 $method = "start::${method}" if ((caller(1)||'') eq 'start');
57 $invocant->$method(@_);
58}
59
11e7c8a5 60package then;
61
62sub AUTOLOAD {
63 my $invocant = shift;
64 my ($method) = our $AUTOLOAD =~ /^then::(.+)$/;
65 my @args = @_;
66 # Need two copies since if we're called on an already complete future
67 # $f will be freed immediately
68 my $ret = my $f = CPS::Future->new;
69 $invocant->on_fail(sub { $f->fail(@_); undef($f); });
70 $invocant->on_done(sub {
71 my ($obj) = @_;
72 my $next = $obj->${\"start::${method}"}(@args);
73 $next->on_done(sub { $f->done(@_); undef($f); });
74 $next->on_fail(sub { $f->fail(@_); undef($f); });
75 });
76 return $ret;
77}
78
dc28afe8 791;
b9a9982d 80
81=head1 NAME
82
83Object::Remote::Future - Asynchronous calling for L<Object::Remote>
84
85=head1 LAME
86
87Shipping prioritised over writing this part up. Blame mst.
88
89=cut