I'm trying to understand how await
/ works async
. I have read several opinions that come to say
async
/await
is nothing more than a sugar-syntax on Promises .
However, the output I'm getting collides head -on with this: I'm not able to explain the outputs of the following code (originally taken from here ).
function sleep( ms ) {
return new Promise( resolve => setTimeout( resolve, ms ) );
}
async function demo( ) {
console.log( 'Taking a break...' );
await sleep( 2000 );
console.log( 'Two seconds later' );
}
async function demo2( ) {
console.log( 'demo2 -> before' );
await demo( );
console.log( 'demo2 -> after' );
}
function demo3( ) {
console.log( 'demo3 -> before' );
demo2( );
console.log( 'demo3 -> after' );
}
demo3( );
The result obtained is:
demo3 -> before
demo2 -> before
Taking a break...
demo3 -> after
... 2 seconds pause ...
Two seconds later
demo2 -> after
However , the expected result is this one:
demo3 -> before
demo2 -> before
Taking a break...
Two seconds later
demo2 -> after
demo3 -> after
In some way that I don't understand, the use of async
/ changes the order of the returns await
! I can't think of any way, using only callbacks and closures , that would cause that behavior.
From the outputs, it seems that the function demo3( )
returns before the function demo2( )
, which is simply impossible according to the classic execution mode that I know.
How does it really async
work / await
? Is it really just a facility to use Promises ? Am I messing myself up looking los 3 pies del gato
?
I'm going to remove the syntactic sugar from your code so it's clear what's being done:
Steps:
demo3NoSugar
, which puts in console'demo3 -> before'
.demo2NoSugar
, which puts in console'demo2 -> before'
.demoNoSugar
, which puts in cosola'Taking a break...'
.sleep(2000)
, which returns a promise that will resolve in 2 seconds. Before returning it, it is attached indemoNoSugar
the order of writing'Two seconds later'
when resolved.'demo2 -> after'
anddemo2NoSugar
returned again.demo3NoSugar
, which doesn't catch the promise, and just ends up writing to console'demo3 -> after'
.Things to keep in mind:
A function that has a
async
, always returns aPromise
. Likewise, a function that returns aPromise
, can be considered to beasync
(and therefore can be used withawait
):It's because you're not using await with demo2 ()
As you can in the console you have:
The await, you should only not use it , for the function that you execute from the main (in this case the call to demo3)