Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

semicolon inside and outside Promise object

Tags:

promise

raku

When I run the following code:

my $timer = Promise.in(2);
my $after = $timer.then({ say "2 seconds are over!"; 'result' });
say $after.result;  # 2 seconds are over
                    # result

I get

2 seconds are over!
result

What is the role of ; inside the then and why if I write

say "2 seconds are over!"; 'result';

do I get the following error?

WARNINGS:
Useless use of constant string "result" in sink context (line 1)
2 seconds are over!

and not :

2 seconds are over!
result

like the first example?

like image 921
smith Avatar asked Jan 26 '16 17:01

smith


People also ask

What is resolve reject in promise?

Promise.reject(reason) Returns a new Promise object that is rejected with the given reason. Promise.resolve(value) Returns a new Promise object that is resolved with the given value.

What is the return value of promise?

Return valueA Promise that is resolved with the given value, or the promise passed as value, if the value was a promise object. It may be either fulfilled or rejected — for example, resolving a rejected promise will still result in a rejected promise.


1 Answers

'result' is the last statement of the block { say "2 seconds are over!"; 'result' }. In Perl languages, semicolons (not newlines) determine the ends of most statements.

In this code:

my $timer = Promise.in(2);
my $after = $timer.then({ say "2 seconds are over!"; 'result' }); # 'result' is what the block returns
say $after.result;  # 2 seconds are over (printed by the say statement)
                    # result ('result' of the block that is stored in $after)

The second line could be rewritten thus:

my $after = $timer.then( {
                          say "2 seconds are over!";
                          'result'
                         }
); # 'result' is what the block returns

That semicolon simply ends the statement say "2 seconds are over!".

Outside of a block, this line

say "2 seconds are over!"; 'result';

is really two statements:

say "2 seconds are over!";  # normal statement
'result';                   # useless statement in this context (hence the warning)

Putting multiple statements in one line rarely changes how they behave:

my $timer = Promise.in(2); my $after = $timer.then({ say "2 seconds are over!"; 'result' }); say $after.result; # Still behaves the same as the original code. ... Do not edit. This is intentionally crammed into one line!
like image 51
Christopher Bottoms Avatar answered Sep 19 '22 04:09

Christopher Bottoms