即使阅读了类似问题的几个答案(例如this和that),不幸的是,我仍然不明白,为什么这段代码没有等待承诺,因此记录了 ['check2' ] 在其他检查点之后。
这是使用代码from this guide的最小示例。在原始代码中,我需要从其他来源获取一些信息,然后我的Express服务器才能开始侦听。
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” 。
答案 0 :(得分:2)
这行代码声明一个async
函数并执行:
(async() => await test())();
到目前为止,没有什么等待结果,并且执行继续进行到console.log("check3")
。
您必须明确等待:
await (async () => await test())();
现在,这还行不通,因为顶级功能不是async
。每当需要调用await
时,都必须确保在async
函数中调用了它。一种方法是将所有内容包装在另一个async
函数中:
(async () => {
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);
}
await (async ()=> await test())();
console.log("check3");
})()
否则,请像其他人建议的那样,将check3
移至您已经拥有的async
函数中。
答案 1 :(得分:1)
这应该做您想要的。您需要将console.log
放在异步函数中。
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");
})();