[英]Why does this `Promise.all()` statement not wait for the promises to resolve?
I wrote a piece of code inside an async function that shall create four users concurrently, save them to a MongoDB and print a message when this is done: 我在异步函数中编写了一段代码,该代码将同时创建四个用户,将它们保存到MongoDB并在完成后打印一条消息:
// Concurrently create dummy users
const dummyUserDict = [
"name1",
"name2",
"name3",
"name4"
];
const dummyUserPromises = dummyUserDict.map(async (name) => {
let user = new User({
_id: new mongoose.Types.ObjectId,
username: name
});
return user
.save()
.then((result) => {
console.log('Created user ' + result.username + '!');
});
});
try {
await Promise.all[dummyUserPromises];
} catch(e) {
console.log(e);
}
console.log('Stop here!');
I'd expect all dummyUserPromises
to be resolved when reaching the end of the code as I explicitly await
them with Promise.all
beforehand. 我希望所有的dummyUserPromises
在到达代码末尾时都会得到解决,因为我事先用Promise.all
明确地await
它们。 When I turn on my debugger and set a breakpoint at console.log('Stop here!')
I find that they are all still pending: 当我打开调试器并在console.log('Stop here!')
处设置断点时,我发现它们都仍在等待处理:
Why is this? 为什么是这样?
You have to call the function: 您必须调用该函数:
await Promise.all(dummyUserPromises)
Using []
you try to access a property of the Promise.all
function, which will result in undefined
and await undefined
won't wait for anything. 使用[]
尝试访问Promise.all
函数的属性,这将导致undefined
和await undefined
不会等待任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.