Raku Books / Perl 6 at a Glance / New Concepts / Promises
anyof and allof
Another pair of factory methods, Promise.anyof and
Promise.allof, creates new promises, which will be only
kept when at least one of the promises (in the case of
anyof) is kept or, in the case of allof, all
of the promises listed at the moment of creation are kept.
One of the useful examples found in the documentation is a timeout keeper to prevent long calculations from hanging the programme.
Create the promise $timeout, which must be kept after a
few seconds, and the code block, which will be running for longer time.
Then, list them both in the constructor of
Promise.anyof.
my $code = start {
sleep 5
}
my $timeout = Promise.in(3);
my $done = Promise.anyof($code, $timeout);
say $done.result;🧵 This program uses concurrency (promises, threads). The in-browser engine (Raku.js) is single-threaded and can’t run it yet — try it on your own computer.
CodeBlockPlaceholder2raku-async my $p = Promise.in(2); my $t = $p.then({say “OK”}); # Prints this in two seconds
say “promised”; # Prints immediately sleep 3;
say “done”; CodeBlockPlaceholder3
promised OK done CodeBlockPlaceholder4
In another example, the promise is broken.
Promise.start({ # A new promise
say 1 / 0 # generates an exception
# (the result of the division is used in say).
}).then({ # The code executed after the broken line.
say "oops"
}).result # This is required so that we wait until
# the result is known.🧵 This program uses concurrency (promises, threads). The in-browser engine (Raku.js) is single-threaded and can’t run it yet — try it on your own computer.
The only output here is the following:
oopsCourse navigation
← in and at | An example →