📘 The anyof and allof methods in Perl 6 promises

📘 The anyof and allof methods in Raku promises

N. B. Perl 6 has been renamed to Raku. Click to read more.

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;

The code should be terminated after three seconds. At this moment, the $timeout promise is kept, and that makes the $done promise be kept, too.

Leave a Reply