简体   繁体   中英

How can await promise resolve if resolve(...) is inside setTimeout?

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM