如果 resolve(...) 在 setTimeout 内,如何等待 promise resolve?
How can await promise resolve if resolve(...) is inside setTimeout?
下面代码的执行顺序是什么?
如果 await 让我们等待“promise”解决,但 resolve(...) 在 setTimeout 中,而 setTimeout 仅在堆栈为空后才执行...我们如何不等待等待?当我们“等待”时,堆栈上不是还有东西吗? await-y setTimeout 是否存在异常,或者我不了解堆栈?
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
基本上是 .then
的替代品——它说“只有在 Promise 解决后才做剩下的事情”。它不会在 await
处冻结解释器 - 它只会暂停当前函数 的执行流程 直到 Promise 解析。
所以
// wait until the promise resolves (*)
读作
可能更准确
// pause execution of this function until the promise resolves (*)
Are there not still things on the stack when we are "await"ing?
是的,f()
returns 在等待 await promise
解决时同步承诺(来自异步函数)。然后脚本不会做任何其他事情,所以调用堆栈完全是空的,直到 setTimeout
宏任务在一秒钟后运行,添加一个调用 resolve
的短任务,它会排队一个微任务,很快就会产生done
正在记录中。
在您的代码中有很多次当前没有活动任务。
下面代码的执行顺序是什么?
如果 await 让我们等待“promise”解决,但 resolve(...) 在 setTimeout 中,而 setTimeout 仅在堆栈为空后才执行...我们如何不等待等待?当我们“等待”时,堆栈上不是还有东西吗? await-y setTimeout 是否存在异常,或者我不了解堆栈?
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
基本上是 .then
的替代品——它说“只有在 Promise 解决后才做剩下的事情”。它不会在 await
处冻结解释器 - 它只会暂停当前函数 的执行流程 直到 Promise 解析。
所以
// wait until the promise resolves (*)
读作
可能更准确// pause execution of this function until the promise resolves (*)
Are there not still things on the stack when we are "await"ing?
是的,f()
returns 在等待 await promise
解决时同步承诺(来自异步函数)。然后脚本不会做任何其他事情,所以调用堆栈完全是空的,直到 setTimeout
宏任务在一秒钟后运行,添加一个调用 resolve
的短任务,它会排队一个微任务,很快就会产生done
正在记录中。
在您的代码中有很多次当前没有活动任务。