Mojo/Promise.pm

filter: Statementstmt 79.4% 155 / 195 Branchbran 79.0% 49 / 62 Conditioncond 57.7% 26 / 45 MC/DCmcdc 40.0% 10 / 25 Subroutinesub 74.2% 52 / 70 Podpod 55.5% 15 / 27 totaltotal 72.4% 307 / 424 CC 52 SCAR 17.2
CC
52
Cov
76%
AWAIT_GET
42.0
_settle_await
20.0
AWAIT_IS_READY
12.0
CRAP 5.6
« Mojolicious/Routes/Route.pm ↑ Summary Mojo/IOLoop/Stream.pm »
1 package Mojo::Promise;
2 33 ▶use Mojo::Base -base;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 33 ▶use Carp qw(carp croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
5 33 ▶use Mojo::Exception;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 33 ▶use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 33 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 33 ▶use constant DEBUG => $ENV{MOJO_PROMISE_DEBUG} || 0;
Subroutine BEGIN: called CC=2 SCAR=7.1
Condition50%1/2
$ENV{'MOJO_PROMISE_DEBUG'} || 0
l!l
033
MC/DC0%0/1
$ENV{'MOJO_PROMISE_DEBUG'} || 0
$ENV{'MOJO_PROMISE_DEBUG'}
Truth table50%1/2
A
A= $ENV{'MOJO_PROMISE_DEBUG'}
Aresult
11
00
10  
11 106 ▶has ioloop => sub { Mojo::IOLoop->singleton }, weak => 1;
Subroutine __ANON__: called CC=1 SCAR=0.0
12  
13 0 ▶sub AWAIT_CHAIN_CANCEL { }
Subroutine AWAIT_CHAIN_CANCEL: not called CC=1 SCAR=0.0
Pod undocumented
14 0 ▶sub AWAIT_CLONE { _await('clone', @_) }
Subroutine AWAIT_CLONE: not called CC=1 SCAR=6.9
Pod undocumented
15 0 ▶sub AWAIT_DONE { _settle_await(resolve => @_) }
Subroutine AWAIT_DONE: not called CC=1 SCAR=6.9
Pod undocumented
16 0 ▶sub AWAIT_FAIL { _settle_await(reject => @_) }
Subroutine AWAIT_FAIL: not called CC=1 SCAR=6.9
Pod undocumented
17  
18 0 ▶sub AWAIT_GET {
Subroutine AWAIT_GET: not called CC=6 SCAR=37.4
Pod undocumented
19 0 my $self = shift;
20 0 ▶ my @results = @{$self->{results} // []};
Condition0%0/2
$self->{"results"} // []
l!l
00
MC/DC0%0/1
$self->{"results"} // []
$self->{"results"}
Truth table0%0/2
A
A= $self->{"results"}
Aresult
11
00
21 0 ▶ return wantarray ? @results : $results[0] if $self->{status} eq 'resolve';
Branch: 2 branches
BranchTrueFalseTotal
if $self->{"status"} eq "resolve" 0 0 0
wantarray ? : 0 0 0
22 0 ▶ die $results[0] if ref $results[0] || $results[0] =~ m!\n!;
Branch: 1 branch
BranchTrueFalseTotal
if ref $results[0] or $results[0] =~ /\n/u 0 0 0
Condition0%0/3
ref $results[0] or $results[0] =~ /\n/u
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $results[0] or $results[0] =~ /\n/u
ref $results[0] $results[0] =~ /\n/u
Truth table0%0/3
A or B
A= ref $results[0]B= $results[0] =~ /\n/u
ABresult
1X1
011
000
23 0 croak $results[0];
24 }
25  
26 0 ▶sub AWAIT_IS_CANCELLED {undef}
Subroutine AWAIT_IS_CANCELLED: not called CC=1 SCAR=6.9
Pod undocumented
27  
28 0 ▶sub AWAIT_IS_READY {
Subroutine AWAIT_IS_READY: not called CC=3 SCAR=24.8
Pod undocumented
29 0 my $self = shift;
30 0 $self->{handled} = 1;
31 0 ▶ return !!$self->{results} && !@{$self->{resolve}} && !@{$self->{reject}};
Condition0%0/6
!$self->{'results'} || @{$self->{'resolve'};} || @{$self->{'reject'};}
l!l&&r!l&&!r
000
not $self->{"results"} or @{$self->{"resolve"};}
l!l&&r!l&&!r
000
MC/DC0%0/3
!$self->{'results'} || @{$self->{'resolve'};} || @{$self->{'reject'};}
not $self->{"results"} @{$self->{"resolve"};} @{$self->{'reject'};}
Truth table0%0/4
not(A) or B || C
A= not $self->{"results"}B= @{$self->{"resolve"};}C= @{$self->{'reject'};}
ABCresult
1XX1
01X1
0011
0000
32 }
33  
34 0 ▶sub AWAIT_NEW_DONE { _await('resolve', @_) }
Subroutine AWAIT_NEW_DONE: not called CC=1 SCAR=6.9
Pod undocumented
35 0 ▶sub AWAIT_NEW_FAIL { _await('reject', @_) }
Subroutine AWAIT_NEW_FAIL: not called CC=1 SCAR=6.9
Pod undocumented
36  
37 0 ▶sub AWAIT_ON_CANCEL { }
Subroutine AWAIT_ON_CANCEL: not called CC=1 SCAR=0.0
Pod undocumented
38  
39 0 ▶sub AWAIT_ON_READY {
Subroutine AWAIT_ON_READY: not called CC=1 SCAR=6.9
Pod undocumented
40 0 my ($self, $cb) = @_;
41 0 push @{$self->{resolve}}, $cb;
42 0 push @{$self->{reject}}, $cb;
43 }
44  
45 0 ▶sub AWAIT_WAIT {
Subroutine AWAIT_WAIT: not called CC=1 SCAR=6.9
Pod undocumented
46 0 my $self = shift;
47 0 ▶ $self->catch(sub { })->wait;
Subroutine __ANON__: not called CC=1 SCAR=6.9
48 0 return $self->AWAIT_GET;
49 }
50  
51 549 ▶sub DESTROY {
Subroutine DESTROY: called CC=5 SCAR=16.1
52 549 my $self = shift;
53 549 ▶ return if $self->{handled} || ($self->{status} // '') ne 'reject' || !$self->{results};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"handled"} or ($self->{"status"} // "") ne "reject" or not $self->{"results"} 542 7 549
Condition87%7/8
$self->{"handled"} or ($self->{"status"} // "") ne "reject" or not $self->{"results"}
l!l&&r!l&&!r
54207
$self->{"handled"} or ($self->{"status"} // "") ne "reject"
l!l&&r!l&&!r
2952477
$self->{"status"} // ""
l!l
2513
MC/DC0%0/3
$self->{"handled"} or ($self->{"status"} // "") ne "reject" or not $self->{"results"}
$self->{"handled"} $self->{"status"} not $self->{"results"}
Truth table50%2/4
A or B or not(C)
A= $self->{"handled"}B= $self->{"status"}C= not $self->{"results"}
ABCresult
1XX1
01X1
0011
0000
54 7 carp "Unhandled rejected promise: @{$self->{results}}";
55 7 warn $self->{debug}->message("-- Destroyed promise\n")->verbose(1)->to_string if DEBUG;
56 }
57  
58 8 ▶sub all { _all(2, @_) }
Subroutine all: called CC=1 SCAR=0.0
Pod documented
59 2 ▶sub all_settled { _all(0, @_) }
Subroutine all_settled: called CC=1 SCAR=0.0
Pod documented
60 2 ▶sub any { _all(3, @_) }
Subroutine any: called CC=1 SCAR=0.0
Pod documented
61  
62 81 ▶sub catch { shift->then(undef, shift) }
Subroutine catch: called CC=1 SCAR=0.0
Pod documented
63  
64 441 ▶sub clone { $_[0]->new->ioloop($_[0]->ioloop) }
Subroutine clone: called CC=1 SCAR=0.0
Pod documented
65  
66 11 ▶sub finally { shift->_finally(1, @_) }
Subroutine finally: called CC=1 SCAR=0.0
Pod documented
67  
68 4 ▶sub map {
Subroutine map: called CC=5 SCAR=16.2
Pod documented
69 4 ▶ my ($class, $options, $cb, @items) = (shift, ref $_[0] eq 'HASH' ? shift : {}, @_);
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 2 2 4
70  
71 4 ▶ return $class->all(map { $_->$cb } @items) if !$options->{concurrency} || @items <= $options->{concurrency};
Branch: 1 branch
BranchTrueFalseTotal
if not $options->{"concurrency"} or @items <= $options->{"concurrency"} 2 2 4
Condition66%2/3
not $options->{"concurrency"} or @items <= $options->{"concurrency"}
l!l&&r!l&&!r
202
MC/DC50%1/2
not $options->{"concurrency"} or @items <= $options->{"concurrency"}
not $options->{"concurrency"} @items <= $options->{"concurrency"}
Truth table66%2/3
not(A) or B
A= not $options->{"concurrency"}B= @items <= $options->{"concurrency"}
ABresult
1X1
011
000
72  
73 2 my @start = map { $_->$cb } splice @items, 0, $options->{concurrency};
74 2 my @wait = map { $start[0]->clone } 0 .. $#items;
75  
76 9 ▶ my $start_next = sub {
Subroutine __ANON__: called CC=3 SCAR=11.2
77 9 ▶ return () unless @items;
Branch: 1 branch
BranchTrueFalseTotal
unless @items 3 6 9
78 6 my $item = shift @items;
79 6 my ($start_next, $chain) = (__SUB__, shift @wait);
80 0 ▶ $_->$cb->then(sub { $chain->resolve(@_); $start_next->() }, sub { $chain->reject(@_); @items = () }) for $item;
Subroutine __ANON__: called CC=1 SCAR=0.6
Subroutine __ANON__: not called CC=1 SCAR=0.6
81 6 return ();
82 2 };
83  
84 2 ▶ $_->then($start_next, sub { }) for @start;
Subroutine __ANON__: called CC=1 SCAR=0.0
85  
86 2 return $class->all(@start, @wait);
87 }
88  
89 551 ▶sub new {
Subroutine new: called CC=2 SCAR=6.9
Pod documented
90 551 my $self = shift->SUPER::new;
91 551 $self->{debug} = Mojo::Exception->new->trace if DEBUG;
92 551 ▶ shift->(sub { $self->resolve(@_) }, sub { $self->reject(@_) }) if @_;
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if @_ 2 549 551
93 551 return $self;
94 }
95  
96 3 ▶sub race { _all(1, @_) }
Subroutine race: called CC=1 SCAR=0.0
Pod documented
97  
98 71 ▶sub reject { shift->_settle('reject', @_) }
Subroutine reject: called CC=1 SCAR=0.0
Pod documented
99 515 ▶sub resolve { shift->_settle('resolve', @_) }
Subroutine resolve: called CC=1 SCAR=0.0
Pod documented
100  
101 376 ▶sub then {
Subroutine then: called CC=2 SCAR=6.9
Pod documented
102 376 my ($self, $resolve, $reject) = @_;
103  
104 376 my $new = $self->clone;
105 376 $self->{handled} = 1;
106 376 ▶ push @{$self->{resolve}}, sub { _then_cb($new, $resolve, 'resolve', @_) };
Subroutine __ANON__: called CC=1 SCAR=0.0
107 376 ▶ push @{$self->{reject}}, sub { _then_cb($new, $reject, 'reject', @_) };
Subroutine __ANON__: called CC=1 SCAR=0.0
108  
109 376 ▶ $self->_defer if $self->{results};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"results"} 89 287 376
110  
111 376 return $new;
112 }
113  
114 2 ▶sub timer { shift->_timer('resolve', @_) }
Subroutine timer: called CC=1 SCAR=0.0
Pod documented
115 3 ▶sub timeout { shift->_timer('reject', @_) }
Subroutine timeout: called CC=1 SCAR=0.0
Pod documented
116  
117 30 ▶sub wait {
Subroutine wait: called CC=3 SCAR=11.0
Pod documented
118 30 my $self = shift;
119 30 ▶ return if (my $loop = $self->ioloop)->is_running;
Branch: 1 branch
BranchTrueFalseTotal
if (my $loop = $self->ioloop)->is_running 0 30 30
120 30 my $done;
121 30 ▶ $self->_finally(0, sub { $done++; $loop->stop })->catch(sub { });
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
122 30 ▶ $loop->start until $done;
Branch: 1 branch
BranchTrueFalseTotal
$done or do { $loop->start } 30 31 61
123 }
124  
125 15 ▶sub _all {
Subroutine _all: called CC=5 SCAR=16.1
126 15 my ($type, $class, @promises) = @_;
127  
128 15 my $all = $promises[0]->clone;
129 15 my $results = [];
130 15 my $remaining = scalar @promises;
131 15 for my $i (0 .. $#promises) {
132  
133 # "race"
134 53 ▶ if ($type == 1) {
Branch: 3 branches
BranchTrueFalseTotal
if ($type == 1) { } 8 45 53
elsif ($type == 2) { } 33 12 45
elsif ($type == 3) { } 6 6 12
135 8 ▶ $promises[$i]->then(sub { $all->resolve(@_); () }, sub { $all->reject(@_); () });
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
136 }
137  
138 # "all"
139 elsif ($type == 2) {
140 $promises[$i]->then(
141 27 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
142 27 $results->[$i] = [@_];
143 27 ▶ $all->resolve(@$results) if --$remaining <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if --$remaining <= 0 6 21 27
144 27 return ();
145 },
146 4 ▶ sub { $all->reject(@_); () }
Subroutine __ANON__: called CC=1 SCAR=0.0
147 33 );
148 }
149  
150 # "any"
151 elsif ($type == 3) {
152 $promises[$i]->then(
153 2 ▶ sub { $all->resolve(@_); () },
Subroutine __ANON__: called CC=1 SCAR=0.0
154 4 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
155 4 $results->[$i] = [@_];
156 4 ▶ $all->reject(@$results) if --$remaining <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if --$remaining <= 0 1 3 4
157 4 return ();
158 }
159 6 );
160 }
161  
162 # "all_settled"
163 else {
164 $promises[$i]->then(
165 5 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
166 5 $results->[$i] = {status => 'fulfilled', value => [@_]};
167 5 ▶ $all->resolve(@$results) if --$remaining <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if --$remaining <= 0 2 3 5
168 5 return ();
169 },
170 1 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
171 1 $results->[$i] = {status => 'rejected', reason => [@_]};
172 1 ▶ $all->resolve(@$results) if --$remaining <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if --$remaining <= 0 0 1 1
173 1 return ();
174 }
175 6 );
176 }
177 }
178  
179 15 return $all;
180 }
181  
182 0 ▶sub _await {
Subroutine _await: not called CC=1 SCAR=6.9
183 0 my ($method, $class) = (shift, shift);
184 0 my $promise = $class->$method(@_);
185 0 $promise->{cycle} = $promise;
186 0 return $promise;
187 }
188  
189 611 ▶sub _defer {
Subroutine _defer: called CC=3 SCAR=11.0
190 611 my $self = shift;
191  
192 611 ▶ return unless my $results = $self->{results};
Branch: 1 branch
BranchTrueFalseTotal
unless my $results = $self->{"results"} 0 611 611
193 611 ▶ my $cbs = $self->{status} eq 'resolve' ? $self->{resolve} : $self->{reject};
Branch: 1 branch
BranchTrueFalseTotal
$self->{'status'} eq 'resolve' ? : 521 90 611
194 611 @{$self}{qw(cycle resolve reject)} = (undef, [], []);
195  
196 611 ▶ $self->ioloop->next_tick(sub { $_->(@$results) for @$cbs });
Subroutine __ANON__: called CC=2 SCAR=6.9
197 }
198  
199 41 ▶sub _finally {
Subroutine _finally: called CC=3 SCAR=11.0
200 41 my ($self, $handled, $finally) = @_;
201  
202 41 my $new = $self->clone;
203 41 ▶ my $cb = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
204 41 my @results = @_;
205 41 ▶ $new->resolve($finally->())->then(sub {@results});
Subroutine __ANON__: called CC=1 SCAR=0.0
206 41 };
207  
208 41 my $before = $self->{handled};
209 41 $self->catch($cb);
210 41 my $next = $self->then($cb);
211 41 ▶ delete $self->{handled} if !$before && !$handled;
Branch: 1 branch
BranchTrueFalseTotal
unless $before or $handled 24 17 41
Condition100%3/3
$before or $handled
l!l&&r!l&&!r
61124
MC/DC100%2/2
$before or $handled
$before $handled
Truth table100%3/3
A or B
A= $beforeB= $handled
ABresult
1X1
011
000
212  
213 41 return $next;
214 }
215  
216 586 ▶sub _settle {
Subroutine _settle: called CC=9 SCAR=22.0
217 586 my ($self, $status, @results) = @_;
218  
219 586 ▶ my $thenable = blessed $results[0] && $results[0]->can('then');
Condition100%3/3
builtin::blessed($results[0]) && $results[0]->can('then')
!ll&&!rl&&r
5181355
MC/DC100%2/2
builtin::blessed($results[0]) && $results[0]->can('then')
builtin::blessed($results[0]) $results[0]->can('then')
Truth table100%3/3
A && B
A= builtin::blessed($results[0])B= $results[0]->can('then')
ABresult
0X0
100
111
220 586 ▶ unless (ref $self) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $self) 38 548 586
221 38 ▶ return $results[0] if $thenable && $status eq 'resolve' && $results[0]->isa('Mojo::Promise');
Branch: 1 branch
BranchTrueFalseTotal
if $thenable and $status eq "resolve" and $results[0]->isa("Mojo::Promise") 4 34 38
Condition66%4/6
$thenable and $status eq "resolve" and $results[0]->isa("Mojo::Promise")
!ll&&!rl&&r
3404
$thenable and $status eq "resolve"
!ll&&!rl&&r
3404
MC/DC33%1/3
$thenable and $status eq "resolve" and $results[0]->isa("Mojo::Promise")
$thenable $status eq "resolve" $results[0]->isa("Mojo::Promise")
Truth table50%2/4
A and B and C
A= $thenableB= $status eq "resolve"C= $results[0]->isa("Mojo::Promise")
ABCresult
0XX0
10X0
1100
1111
222 34 $self = $self->new;
223 }
224  
225 582 ▶ if ($thenable && $status eq 'resolve') {
Branch: 2 branches
BranchTrueFalseTotal
if ($thenable and $status eq 'resolve') { } 50 532 582
elsif (not $self->{'results'}) { } 522 10 532
Condition100%3/3
$thenable and $status eq "resolve"
!ll&&!rl&&r
531150
MC/DC100%2/2
$thenable and $status eq "resolve"
$thenable $status eq "resolve"
Truth table100%3/3
A and B
A= $thenableB= $status eq "resolve"
ABresult
0X0
100
111
226 50 ▶ $results[0]->then(sub { $self->resolve(@_); () }, sub { $self->reject(@_); () });
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
227 }
228 elsif (!$self->{results}) {
229 522 @{$self}{qw(results status)} = (\@results, $status);
230 522 $self->_defer;
231 }
232  
233 582 return $self;
234 }
235  
236 0 ▶sub _settle_await {
Subroutine _settle_await: not called CC=4 SCAR=30.0
237 0 my ($status, $self, @results) = @_;
238 0 ▶ return $results[0]->then(sub { $self->resolve(@_); () }, sub { $self->reject(@_); () })
Subroutine __ANON__: not called CC=1 SCAR=6.9
Subroutine __ANON__: not called CC=1 SCAR=6.9
239 0 ▶ if blessed $results[0] && $results[0]->can('then');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($results[0]) and $results[0]->can("then") 0 0 0
Condition0%0/3
builtin::blessed($results[0]) and $results[0]->can("then")
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($results[0]) and $results[0]->can("then")
builtin::blessed($results[0]) $results[0]->can("then")
Truth table0%0/3
A and B
A= builtin::blessed($results[0])B= $results[0]->can("then")
ABresult
0X0
100
111
240 0 ▶ @{$self}{qw(results status)} = ([@results], $status) if !$self->{results};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"results"} 0 0 0
241 0 $self->_defer;
242 }
243  
244 350 ▶sub _then_cb {
Subroutine _then_cb: called CC=3 SCAR=11.0
245 350 my ($new, $cb, $method, @results) = @_;
246  
247 350 ▶ return $new->$method(@results) unless defined $cb;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $cb 73 277 350
248  
249 277 my @res;
250 277 ▶ return $new->reject($@) unless eval { @res = $cb->(@results); 1 };
Branch: 1 branch
BranchTrueFalseTotal
unless eval { do { @res = &$cb(@results); 1 } } 2 275 277
251 275 return $new->resolve(@res);
252 }
253  
254 5 ▶sub _timer {
Subroutine _timer: called CC=4 SCAR=13.9
255 5 my ($self, $method, $after, @results) = @_;
256 5 ▶ $self = $self->new unless ref $self;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self 3 2 5
257 5 ▶ $results[0] = 'Promise timeout' if $method eq 'reject' && !@results;
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "reject" and not @results 1 4 5
Condition100%3/3
$method eq "reject" and not @results
!ll&&!rl&&r
221
MC/DC100%2/2
$method eq "reject" and not @results
$method eq "reject" not @results
Truth table100%3/3
A and not(B)
A= $method eq "reject"B= not @results
ABresult
0X0
100
111
258 5 ▶ $self->ioloop->timer($after => sub { $self->$method(@results) });
Subroutine __ANON__: called CC=1 SCAR=0.0
259 5 return $self;
260 }
261  
262 33 1;
263  
264 =encoding utf8
265  
266 =head1 NAME
267  
268 Mojo::Promise - Promises/A+
269  
270 =head1 SYNOPSIS
271  
272 use Mojo::Promise;
273 use Mojo::UserAgent;
274  
275 # Wrap continuation-passing style APIs with promises
276 my $ua = Mojo::UserAgent->new;
277 sub get_p {
278 my $promise = Mojo::Promise->new;
279 $ua->get(@_ => sub ($ua, $tx) {
280 my $err = $tx->error;
281 if (!$err || $err->{code}) { $promise->resolve($tx) }
282 else { $promise->reject($err->{message}) }
283 });
284 return $promise;
285 }
286  
287 # Perform non-blocking operations sequentially
288 get_p('https://mojolicious.org')->then(sub ($mojo) {
289 say $mojo->res->code;
290 return get_p('https://metacpan.org');
291 })->then(sub ($cpan) {
292 say $cpan->res->code;
293 })->catch(sub ($err) {
294 warn "Something went wrong: $err";
295 })->wait;
296  
297 # Synchronize non-blocking operations (all)
298 my $mojo = get_p('https://mojolicious.org');
299 my $cpan = get_p('https://metacpan.org');
300 Mojo::Promise->all($mojo, $cpan)->then(sub ($mojo, $cpan) {
301 say $mojo->[0]->res->code;
302 say $cpan->[0]->res->code;
303 })->catch(sub ($err) {
304 warn "Something went wrong: $err";
305 })->wait;
306  
307 # Synchronize non-blocking operations (race)
308 my $mojo = get_p('https://mojolicious.org');
309 my $cpan = get_p('https://metacpan.org');
310 Mojo::Promise->race($mojo, $cpan)->then(sub ($tx) {
311 say $tx->req->url, ' won!';
312 })->catch(sub ($err) {
313 warn "Something went wrong: $err";
314 })->wait;
315  
316 =head1 DESCRIPTION
317  
318 L<Mojo::Promise> is a Perl-ish implementation of L<Promises/A+|https://promisesaplus.com> and a superset of L<ES6
319 Promises|https://duckduckgo.com/?q=\mdn%20Promise>.
320  
321 =head1 STATES
322  
323 A promise is an object representing the eventual completion or failure of a non-blocking operation. It allows
324 non-blocking functions to return values, like blocking functions. But instead of immediately returning the final value,
325 the non-blocking function returns a promise to supply the value at some point in the future.
326  
327 A promise can be in one of three states:
328  
329 =over 2
330  
331 =item pending
332  
333 Initial state, neither fulfilled nor rejected.
334  
335 =item fulfilled
336  
337 Meaning that the operation completed successfully.
338  
339 =item rejected
340  
341 Meaning that the operation failed.
342  
343 =back
344  
345 A pending promise can either be fulfilled with a value or rejected with a reason. When either happens, the associated
346 handlers queued up by a promise's L</"then"> method are called.
347  
348 =head1 ATTRIBUTES
349  
350 L<Mojo::Promise> implements the following attributes.
351  
352 =head2 ioloop
353  
354 my $loop = $promise->ioloop;
355 $promise = $promise->ioloop(Mojo::IOLoop->new);
356  
357 Event loop object to control, defaults to the global L<Mojo::IOLoop> singleton. Note that this attribute is weakened.
358  
359 =head1 METHODS
360  
361 L<Mojo::Promise> inherits all methods from L<Mojo::Base> and implements the following new ones.
362  
363 =head2 all
364  
365 my $new = Mojo::Promise->all(@promises);
366  
367 Returns a new L<Mojo::Promise> object that either fulfills when all of the passed L<Mojo::Promise> objects have
368 fulfilled or rejects as soon as one of them rejects. If the returned promise fulfills, it is fulfilled with the values
369 from the fulfilled promises in the same order as the passed promises.
370  
371 =head2 all_settled
372  
373 my $new = Mojo::Promise->all_settled(@promises);
374  
375 Returns a new L<Mojo::Promise> object that fulfills when all of the passed L<Mojo::Promise> objects have fulfilled or
376 rejected, with hash references that describe the outcome of each promise.
377  
378 =head2 any
379  
380 my $new = Mojo::Promise->any(@promises);
381  
382 Returns a new L<Mojo::Promise> object that fulfills as soon as one of the passed L<Mojo::Promise> objects fulfills,
383 with the value from that promise.
384  
385 =head2 catch
386  
387 my $new = $promise->catch(sub {...});
388  
389 Appends a rejection handler callback to the promise, and returns a new L<Mojo::Promise> object resolving to the return
390 value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled.
391  
392 # Longer version
393 my $new = $promise->then(undef, sub {...});
394  
395 # Pass along the rejection reason
396 $promise->catch(sub (@reason) {
397 warn "Something went wrong: $reason[0]";
398 return @reason;
399 });
400  
401 # Change the rejection reason
402 $promise->catch(sub (@reason) { "This is bad: $reason[0]" });
403  
404 =head2 clone
405  
406 my $new = $promise->clone;
407  
408 Return a new L<Mojo::Promise> object cloned from this promise that is still pending.
409  
410 =head2 finally
411  
412 my $new = $promise->finally(sub {...});
413  
414 Appends a fulfillment and rejection handler to the promise, and returns a new L<Mojo::Promise> object resolving to the
415 original fulfillment value or rejection reason.
416  
417 # Do something on fulfillment and rejection
418 $promise->finally(sub { say "We are done!" });
419  
420 =head2 map
421  
422 my $new = Mojo::Promise->map(sub {...}, @items);
423 my $new = Mojo::Promise->map({concurrency => 3}, sub {...}, @items);
424  
425 Apply a function that returns a L<Mojo::Promise> to each item in a list of items while optionally limiting concurrency.
426 Returns a L<Mojo::Promise> that collects the results in the same manner as L</all>. If any item's promise is rejected,
427 any remaining items which have not yet been mapped will not be.
428  
429 # Perform 3 requests at a time concurrently
430 Mojo::Promise->map({concurrency => 3}, sub { $ua->get_p($_) }, @urls)
431 ->then(sub{ say $_->[0]->res->dom->at('title')->text for @_ });
432  
433 These options are currently available:
434  
435 =over 2
436  
437 =item concurrency
438  
439 concurrency => 3
440  
441 The maximum number of items that are in progress at the same time.
442  
443 =back
444  
445 =head2 new
446  
447 my $promise = Mojo::Promise->new;
448 my $promise = Mojo::Promise->new(sub {...});
449  
450 Construct a new L<Mojo::Promise> object.
451  
452 # Wrap a continuation-passing style API
453 my $promise = Mojo::Promise->new(sub ($resolve, $reject) {
454 Mojo::IOLoop->timer(5 => sub {
455 if (int rand 2) { $resolve->('Lucky!') }
456 else { $reject->('Unlucky!') }
457 });
458 });
459  
460 =head2 race
461  
462 my $new = Mojo::Promise->race(@promises);
463  
464 Returns a new L<Mojo::Promise> object that fulfills or rejects as soon as one of the passed L<Mojo::Promise> objects
465 fulfills or rejects, with the value or reason from that promise.
466  
467 =head2 reject
468  
469 my $new = Mojo::Promise->reject(@reason);
470 $promise = $promise->reject(@reason);
471  
472 Build rejected L<Mojo::Promise> object or reject the promise with one or more rejection reasons.
473  
474 # Longer version
475 my $promise = Mojo::Promise->new->reject(@reason);
476  
477 =head2 resolve
478  
479 my $new = Mojo::Promise->resolve(@value);
480 $promise = $promise->resolve(@value);
481  
482 Build resolved L<Mojo::Promise> object or resolve the promise with one or more fulfillment values.
483  
484 # Longer version
485 my $promise = Mojo::Promise->new->resolve(@value);
486  
487 =head2 then
488  
489 my $new = $promise->then(sub {...});
490 my $new = $promise->then(sub {...}, sub {...});
491 my $new = $promise->then(undef, sub {...});
492  
493 Appends fulfillment and rejection handlers to the promise, and returns a new L<Mojo::Promise> object resolving to the
494 return value of the called handler.
495  
496 # Pass along the fulfillment value or rejection reason
497 $promise->then(
498 sub (@value) {
499 say "The result is $value[0]";
500 return @value;
501 },
502 sub (@reason) {
503 warn "Something went wrong: $reason[0]";
504 return @reason;
505 }
506 );
507  
508 # Change the fulfillment value or rejection reason
509 $promise->then(
510 sub (@value) { return "This is good: $value[0]" },
511 sub (@reason) { return "This is bad: $reason[0]" }
512 );
513  
514 =head2 timer
515  
516 my $new = Mojo::Promise->timer(5 => 'Success!');
517 $promise = $promise->timer(5 => 'Success!');
518 $promise = $promise->timer(5);
519  
520 Create a new L<Mojo::Promise> object with a timer or attach a timer to an existing promise. The promise will be
521 resolved after the given amount of time in seconds with or without a value, unless it has already been settled. Note
522 that this does not delay the resolution of an existing promise, to add a delay to a promise chain you have to return a
523 new timer promise instead.
524  
525 # Wait 5 seconds between two steps
526 $promise->then(sub { Mojo::Promise->timer(5) })->then(sub { say 'Five seconds later' });
527  
528 =head2 timeout
529  
530 my $new = Mojo::Promise->timeout(5 => 'Timeout!');
531 $promise = $promise->timeout(5 => 'Timeout!');
532 $promise = $promise->timeout(5);
533  
534 Create a new L<Mojo::Promise> object with a timeout or attach a timeout to an existing promise. The promise will be
535 rejected after the given amount of time in seconds with a reason, which defaults to C<Promise timeout>, unless it has
536 already been settled.
537  
538 =head2 wait
539  
540 $promise->wait;
541  
542 Start L</"ioloop"> and stop it again once the promise has been fulfilled or rejected, does nothing when L</"ioloop"> is
543 already running.
544  
545 =head1 DEBUGGING
546  
547 You can set the C<MOJO_PROMISE_DEBUG> environment variable to get some advanced diagnostics information printed to
548 C<STDERR>.
549  
550 MOJO_PROMISE_DEBUG=1
551  
552 =head1 SEE ALSO
553  
554 L<Mojolicious>, L<Mojolicious::Guides>, L<https://mojolicious.org>.
555  
556 =cut
« Mojolicious/Routes/Route.pm ↑ Summary Mojo/IOLoop/Stream.pm »