No, because the Promise
implicitly returned by funcao2
is solved soon after the function is called (with a tiny delay due to the way these operations are stacked by JS).
This makes the await
do not wait for 2
be printed on the console, which will only be done after 1 second from call to function setTimeout
.
If you want 1, 2 and 3 to be printed in order, funcao2
must return a Promise
wait for a second of the setTimeout
. In that case, a Promise
will have to be explicitly returned, which makes the annotation async
unnecessary in funcao2
. Behold:
async function funcao1() {
console.log(1);
await funcao2();
console.log(3);
}
function funcao2() {
return new Promise((resolve) => {
setTimeout(() => {
console.log(2);
resolve();
}, 1000);
});
}
funcao1();
Do it without setTimeout to see, calling the console.log directly that makes it easier to understand. This has nothing to do with async, if do with normal synchronous function call gives in it (will go out of order because of the timeout, which simply "schedule" the call, out of normal flow).
– Bacco