我无法理解异步函数在 JavaScript 中的工作原理。我们来看下面的代码:
async () => {
console.log(1);
setTimeout(() => console.log(2)
, 2000)
console.log(3);
}
我希望在执行进一步的代码之前,在异步内部调用同步函数应该阻塞线程。所以我希望得到 1 -> 2 -> 3
而不是我得到 1 -> 3 -> 2
。找不到发生这种情况的原因以及如何阻止线程接收输出 1 -> 2 -> 3
的解释。
我正在使用 Node 12 和无服务器框架。
最佳答案
async
本身不会等到 setTimeout
的执行按您的预期完成。正如您可以从文档中阅读的那样 - 在此处查找 async
:
An async function can contain an await expression that pauses the execution of the async function to wait for the passed Promise's resolution, then resumes the
async
function's execution and evaluates as the resolved value.
刚刚构建了一个快速示例,以了解 async
和 await
解决方案之间的区别,并仅使用 setTimeout
(如示例中所示)。
考虑以下示例:
const getPromise = async () => {
return new Promise((resolve) => {
setTimeout(resolve, 3000);
});
}
const run = async () => {
console.log('run started');
setTimeout(() => console.log('setTimeout finised'), 2000);
console.log('setTimeout started');
const promise = await getPromise();
console.log('Promise resolved');
console.log('run finished');
}
run();
步骤说明:
- 记录函数
run
执行开始的情况 - 将一个事件附加到
setTimeout
,该事件将在大约 2 秒内完成 - 登录到
setTimeout
启动的控制台 - 使用
getPromise
函数创建 Promise,并使用await
关键字等待resolve
- 大约 2 秒内
setTimeout
记录它已完成 - 在
Promise
后大约 3 秒内调用resolve
函数 run
函数在resolve
和日志记录后完成执行。
我希望能帮助您理解这部分代码。
关于javascript - 在异步函数中调用同步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59694469/