首页 > 解决方案 > 在 node.js 中,为什么我的 Promise.all 没有看到我之前的 for 循环创建的一系列承诺?

问题描述

我的目标是遍历对象数组并将它们添加到 MongoDB 数据库中,如果该对象在数据库中尚不存在。我希望我的代码等到所有对象都添加完毕后再继续,所以我添加了一个 Promise.all 函数,并将任何 insertOne 函数添加到一个名为“promises”的承诺数组中。

//Loop through currentActiveMarkets, add any insertOne requests to promises array
var promises = [];
for (let market of currentActiveMarkets){
    console.log("   Looking to see if marketHash exists: " + market.marketHash)
    //Search if marketHash already exists in MongoDB
    dbo.collection("bettingmarkets").findOne({ marketHash: market.marketHash }, function(err, exists) { 
        if (err) throw err;
        //if currentActiveMarkets is found in MongoDB already, do nothing
        if (exists) {
            console.log("   marketHash " + market.marketHash + " exists") 
        //if currentActiveMarkets is not found in MongoDB, insert it by adding to promise list
        } else { 
            console.log("   marketHash doesn't exist")
            var promise = new Promise(function(resolve, refuse){
                dbo.collection("bettingmarkets").insertOne(market, function(err, res) {
                    if (err) throw err;
                    console.log("   marketHash added to MongoDB: " + market.marketHash);
                    return resolve;
                })
            })
            //logging confirms promises are being added to promises array
            console.log("promise: " + promise);
            promises.push(promise);
            console.log("promises: " + promises);
        };
    });
};
Promise.all(promises).then(() => {
    console.log("   All non-duplicate ActiveMarkets have been added to MongoDB.");
    console.log(promises)// why are no promises making it into this Promise All array????
    })
    .catch((e) => {
        console.log("   Error with Promise All: " + e);
    });

问题是 Promise.all 似乎在 for 循环内运行任何内容之前正在执行。当 Promise.all 运行时,日志显示一个空的 Promise 数组 == []。

在实际的 for 循环中,日志显示每次调用 insertOne 时我的 promise 对象都被添加到 promises 数组中,但就像我说的,Promise.all 没有在数组中看到它们。Promise.all 在将 Promise 添加到 Promise 数组之前执行。

如何更改我的代码,以便 Promise.all(promises) 在 for 循环完成并且承诺已添加到承诺数组之前不会执行?

标签: javascriptnode.jsfor-looppromise

解决方案


通过查看您的代码,我会说,“问题”在于:dbo.collection("bettingmarkets").findOne().

此代码是异步的。这意味着,它可能会在您完成 for 循环后运行。

MongoDB 在其关于db.collection.findOne()的文档中有点模棱两可,但如果它恰好与此文档匹配,您可以使用 Promise 而不是回调。

在这种情况下,您可以使用 anArray.prototype.map来填充您的数组(类似于 antino 的响应)。


推荐阅读