[英]Why does this `Promise.all()` statement not wait for the promises to resolve?
我在異步函數中編寫了一段代碼,該代碼將同時創建四個用戶,將它們保存到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!');
我希望所有的dummyUserPromises
在到達代碼末尾時都會得到解決,因為我事先用Promise.all
明確地await
它們。 當我打開調試器並在console.log('Stop here!')
處設置斷點時,我發現它們都仍在等待處理:
為什么是這樣?
您必須調用該函數:
await Promise.all(dummyUserPromises)
使用[]
嘗試訪問Promise.all
函數的屬性,這將導致undefined
和await undefined
不會等待任何內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.