Raku Books / Perl 6 at a Glance / New Concepts / Promises

Basics

The Promise.new constructor builds a new promise. The status of it can be read using the status method. Before any other actions are done with the promise, its status remains to be Planned.

my $p = Promise.new;
say $p.status; # Planned

🧵 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.new; $p.keep; say $p.status; # Kept CodeBlockPlaceholder3raku-async my $p = Promise.new; say $p.status; # Planned

$p.break; say $p.status; # Broken CodeBlockPlaceholder4

Instead of asking for a status, the whole promise object can be converted to a Boolean value. There is the Bool method for that; alternatively, the unary operator ? can be used instead.

say $p.Bool;
say ?$p;

Keep in mind that as a Boolean value can only take one of the two possible states, the result of the Boolean typecast is not a full replacement for the status method.

There is another method for getting a result called result. It returns truth if the promise has been kept.

my $p = Promise.new;
$p.keep;
say $p.result; # True

🧵 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.

CodeBlockPlaceholder7raku-async my $p = Promise.new; $p.break; say $p.result; CodeBlockPlaceholder8

Run this programme and get the exception details in the console.

Tried to get the result of a broken Promise

CodeBlockPlaceholder10raku-async my $p = Promise.new; $p.break; try { say $p.result; } CodeBlockPlaceholder11

The cause method, when called instead of the result, will explain the details for the broken promise. The method cannot be called on the kept promise:

Can only call cause on a broken promise (status: Kept)

Like with exceptions, both kept and broken promises can be attributed to a message or an object. In this case, the result will return that message instead of a bare True or False.

This is how a message is passed for the kept promise:

my $p = Promise.new;
$p.keep('All done');
say $p.status; # Kept
say $p.result; # All done

🧵 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.

This is how it works with the broken promise:

my $p = Promise.new;
$p.break('Timeout');
say $p.status; # Broken
say $p.cause;  # Timeout

🧵 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.

Course navigation

Promises   |   Factory methods