Skip to content

Commit 347e492

Browse files
committed
[Promise] incorporate feedback from jnthn++ and lizmat++
* explain that you can only keep and break promises yourself if you created them with .new * timeout example for Promise.anyof
1 parent 43b8eb8 commit 347e492

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

lib/Type/Promise.pod

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,32 @@ combining promises, and waiting for results.
1717
say $p.status; # Planned
1818
$p.result; # waits for the computation to finish
1919
20+
There are two typical scenarios for using promises. The first is to use a
21+
factory method (C<start>, C<in>, C<anyof>, C<allof>) on the type object; those
22+
will take care the that promise is automatically kept or broken for you, and
23+
you can't call C<break> or C<keep> on these promises yourself.
24+
25+
The second is to create your promises yourself with C<Promise.new>. If you
26+
want to ensure that only your code can keep or break the promise, you can use
27+
the C<vow> method to get a unique handle, and call C<keep> or C<break> on that
28+
promise:
29+
30+
sub async-get-with-promise($user-agent, $url) {
31+
my $p = Promise.new;
32+
my $v = $p.vow;
33+
34+
# do an asynchronous call on a fictive user agent
35+
# call, return the promise:
36+
$user-agent.async-get($url,
37+
on-error => -> $error {
38+
$v.break($error);
39+
},
40+
on-success => -> $response {
41+
$v.keep($response);
42+
}
43+
);
44+
return $p;
45+
}
2046
2147
=head1 Methods
2248
@@ -72,7 +98,15 @@ Returns a new promise that will be kept when the any of the promises passed as
7298
arguments are kept, and will be broken when all of the argument promises are
7399
broken.
74100
75-
(TODO: example)
101+
You can use this to wait at most a number of seconds for a promise:
102+
103+
my $timeout = 5;
104+
await Promise.anyof(
105+
Promise.in($timeout),
106+
start {
107+
# do a potentially long-running calculation here
108+
},
109+
);
76110
77111
=head2 method then
78112

0 commit comments

Comments
 (0)