【问题标题】:Node | Promise not finishing节点 |承诺没有完成
【发布时间】:2021-10-19 21:50:09
【问题描述】:

我正在尝试从 MongoDB 获取不同集合的数据。我用 Node.js 和 Promise 做到这一点。下面是一些基本代码:

await Promise.all(
        ["a", "b", "c"].map(async (collection) => {
            const query: any = { "_id": { $in: ids} }
            // I just use toArray for demonstration purposes
            const data = await this.db!.collection(collection).find(query).toArray()
            for (let i = 0; i < data.length; i++) {
                const document = data[i]
                // Do something...
            }
            console.log(collection)
            return true
        })
    )
 console.log("done")

我为八个集合(a、b、...、h)执行此操作。数据从数据库中获取并在可接受的时间内正确处理。然后它打印每个集合的名称。但它不会继续。它没有完成承诺并转到完成的日志。

该方法在 JS-Worker 任务中被调用。这里可能是什么问题?我从来没有遇到过承诺和更大数据量的问题。

【问题讨论】:

  • console.log 等待 Promise.all 调用时会发生什么?另外,为了确保 console.log('done') 与对 Promise.all 的调用在同一个异步函数体中,对吧?
  • @Xeelley Promise.all 也接受任何数组。Promise.all([1,2,3,false,undefined]).then(console.log); 是有效代码。
  • @BrunoFarias 嗯,所以我错了,对不起,我的错,我删除了我之前的建议
  • @BrunoFarias 它打印一个由八个真实元素组成的数组

标签: javascript node.js typescript mongodb es6-promise


【解决方案1】:

这实际上是一个同步执行。在上一个数据库调用完成之前,它不会进入下一个集合。箭头函数应该返回一个 promise。

解决办法就是这样重新排列代码-

async function callDb(collection) {
    const query: any = { "_id": { $in: ids} }
    // I just use toArray for demonstration purposes
    const data = await this.db!.collection(collection).find(query).toArray()

    for (let i = 0; i < data.length; i++) {
        const document = data[i]
        // Do something...
    }
    console.log(collection)
    return true
}

await Promise.all(
    ["a", "b", "c"].map(callDb)
)

console.log("done")

【讨论】:

  • 我尝试了您的解决方案。但我不认为异步函数被称为同步。如果我先打印集合,那么所有输出都会同时出现。此外,MongoDB 请求不是瓶颈。直到收集最后一个日志的时间对我来说是可以的。但后来卡住了。
猜你喜欢
  • 2014-07-25
  • 2021-10-20
  • 2020-10-25
  • 1970-01-01
  • 1970-01-01
  • 2016-05-17
  • 2021-12-23
  • 2018-09-26
  • 1970-01-01
相关资源
最近更新 更多