【问题标题】:Why does this `Promise.all()` statement not wait for the promises to resolve?为什么这个 `Promise.all()` 语句不等待承诺解决?
【发布时间】:2019-05-23 16:22:01
【问题描述】:

我在异步函数中编写了一段代码,该函数将同时创建四个用户,将它们保存到 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!') 处设置断点时,我发现它们仍然处于待处理状态:

这是为什么?

【问题讨论】:

  • 因为您使用方括号而不是括号?你为什么这样做?
  • 你有一个错字是all()而不是all[]

标签: javascript asynchronous mongoose async-await


【解决方案1】:

你必须调用函数:

 await Promise.all(dummyUserPromises)

使用[],您尝试访问Promise.all 函数的属性,这将导致undefinedawait undefined 不会等待任何内容。

【讨论】:

    猜你喜欢
    • 2019-04-29
    • 2021-08-02
    • 2021-12-22
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多