【发布时间】:2020-03-05 21:56:05
【问题描述】:
即使在阅读了几个类似问题的答案(例如 this 和 that)之后,我仍然不明白为什么这段代码不等待承诺并因此记录 ['check2'] 最后在其他检查站之后。
这是一个使用代码from this guide 的最小示例。在原始代码中,我需要先从不同来源获取一些信息,然后我的快速服务器才能开始收听。
console.log("check1");
const resolveInTwoSeconds = () => {
return new Promise((resolve) => {
setTimeout(() => resolve("check2"), 2000);
})
};
async function test() {
const asyncFunctions = [
resolveInTwoSeconds()
];
const results = await Promise.all(asyncFunctions);
console.log(results);
}
(async() => await test())();
console.log("check3");
编辑: 想象一下“check3”是很多依赖于 test() 副作用的代码。 因此,我希望它在 check2 打印后运行。 但是我在这里使用 await,所以 我不必更改或移动“check3”。
【问题讨论】:
-
它应该按预期工作,并在 2 秒后记录 check2
-
如果您希望
"check3"最后记录,您应该在最后一个异步 IIFE 中添加该语句 within。 -
你能否描述你的问题,测试你的代码和工作发现在 Promise.all 方面
-
@EugenSunic "...为什么这段代码...记录 ['check2'] 在其他检查点之后。" - 预期输出:
check 1 -> check 2 -> check 3。实际输出:check1 -> check 3 -> check 2 -
async/await只是 Promise 和.then()的语法糖。任何不在.then()调用中的东西(在await之后的函数调用中)都不会“等待”。