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

start

The start method creates a promise containing a block of code. There is an alternative way to create a promise by calling Promise.start via the start keyword.

my $p = start {
    42
}

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

(Note that in Perl 6, a semicolon is assumed after a closing brace at the end of a line.)

The start method returns a promise. It will be broken if the code block throws an exception. If there are no exceptions, the promise will be kept.

my $p = start {
    42
}
say $p.result; # 42
say $p.status; # Kept

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

CodeBlockPlaceholder3raku-async my $p = start { sleep 1; 42 } say $p.status; # Planned say $p.result; # 42 say $p.status; # Kept CodeBlockPlaceholder4

Now, it can be clearly seen that the first call of $p.status is happening immediately after the promise has been created and informs us that the promise is Planned. Later, after the result unblocked the programme flow in about a second, the second call of $p.status prints Kept, which means that the execution of the code block is completed and no exceptions were thrown.

Would the code block generate an exception, the promise becomes broken.

my $p = start {
    die;
}
try {
    say $p.result;
}
say $p.status; # This line will be executed
               # and will print 'Broken'

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

CodeBlockPlaceholder6raku-async # $p1 is Kept my $p1 = start { my $inf = 1 / 0; }

$p2 is Broken

my $p2 = start { my $inf = 1 / 0; say $inf; }

sleep 1; # Wait to make sure the code blocks are done

say $p1.status; # Kept say $p2.status; # Broken ```

Course navigation

Factory methods   |   in and at