Reputation: 152
What is the order of execution for code below?
If await makes us wait for "promise" to resolve, but resolve(...) is inside a setTimeout, and a setTimeout only gets executed after the stack is empty... How are we not frozen on await? Are there not still things on the stack when we are "await"ing? Is there some exception to an await-y setTimeout , or am I not understanding the stack?
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // wait until the promise resolves (*)
alert(result); // "done!"
}
f();
Upvotes: 1
Views: 748
Reputation: 370699
await
is basically a substitute for .then
- it says "do the rest of this stuff only once the Promise has resolved". It does not freeze the interpreter at the point of the await
- it only pauses execution flow for the current function until the Promise resolves.
So
// wait until the promise resolves (*)
might be more accurately read as
// pause execution of this function until the promise resolves (*)
Are there not still things on the stack when we are "await"ing?
Yes, f()
returns a Promise (from the async function) synchronously while the await promise
is being waited on to resolve. Then the script doesn't do anything else, so the call stack lies completely empty until the setTimeout
macrotask runs a second later, adding a short task that calls resolve
, which queues a microtask that shortly results in done
being logged.
There are a number of times during your code in which there is no currently active task.
Upvotes: 1