for 循环内的 Node js promise 总是打印 Promise { <pending>} [英] Node js promise inside for loop always prints Promise { <pending> }

查看:118
本文介绍了for 循环内的 Node js promise 总是打印 Promise { <pending>}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决 node js 中 for 循环内的承诺.在我的代码中,我有一个 for 循环,我在其中调用了一个返回承诺的函数 findincollection.然后我将数据推送到 finalresult 数组并在 for 循环完成后解析它.但我面临的问题是它不能解决完整的数据.在解决所有承诺之前,for 循环执行已完成.行 console.log(p1); 总是打印 Promise { } 但它最终得到解决,正如您在 p1.then() 语句中的代码中看到的那样,我一一获取数据.但是 finalresult 数组解析得太早.我也想知道为什么我总是得到 Promise { } 即使承诺最终仍然得到解决.请看看我下面的代码:

I'm trying to resolve a promise inside a for-loop in node js. In my code, I have a for loop in which I call a function findincollection that returns a promise. Then I push the data to finalresult array and resolve it once the for loop completes. But the issue I'm facing is it doesn't resolve the complete data. The for loop execution is getting finished before all the promises are resolved. The line console.log(p1); always prints Promise { } but it eventually gets resolved as you can see in my code in the p1.then() statement, I do get the data one by one. But the finalresult array resolves too early. I also want to know why I always get Promise { } even when the promises are still getting resolved eventually. Please have a look at my code below :

var mob = [123, 456, 789];
var list = [1, 2, 3, 4, 5, 6, 7, 8];
var res = [];
var finalresult = [];
for (y = 0; y < list.length; y++) {
    const p1 = findincollection(list[y], mob, savetofile);
    console.log(p1); //always prints Promise { <pending> } 8 times
    p1.then(function(dt) {
        finalresult.push(dt); //pushes all 3 objects one by one
        console.log(dt); //prints 3 objects one by one
        client.close();
        if (y == (collist.length)) { //check if the loop has reached the last index
            resolve(finalresult); //resolves the finalresult array with 1 object only instead of 3. I want this part to resolve the complete finalresult array i.e with all 3 objects.
        }
    });
}

const findincollection = function(index, mob, save) {
    return new Promise((resolve, reject) => {
        MongoClient.connect(url, function(err, client) {
            assert.equal(null, err);
            const db = client.db(dbName);
            const collection = db.collection(col);
            collection.find({ 'Numbers': { $in: mob } }).toArray(function(err, docs) {
                const c = save(index, docs);
                c.then(function(m) {
                    console.log(m); //print's Saved 3 times as the mob array length is 3
                    client.close();
                    return resolve(res);
                })
            });
        });
    });
}

const save = function(index, data) {
    return new Promise((resolve, reject) => {
        if (data.length > 0) {
            for (var k = 0; k < data.length; k++) {
                res.push(data[k]);
            }
            fs.appendFile('textlogs/' + index + '.txt', data, function(err) {
                if (err) throw err;
                resolve('Saved');
            });
        }
    });
}

我不知道如何让循环等到所有承诺都得到解决或使代码同步,然后只解决 finalresult 数组?我该怎么做?

I'm not able to figure out how to make the loop wait until all the promises are resolved or make the code synchronous and then only resolve the finalresult array? How do I do it?

推荐答案

这里你需要的是 Promise.all().它返回一个新的承诺,一旦所有通过的承诺得到解决,它就会得到解决.

What you need here is Promise.all(). It returns a new promise, which gets resolved once all passed promises get resolved.

您可以尝试类似的操作:

You can try something similar to:

var promises = [];

for (y = 0; y < list.length; y++) {
    promises.push(findincollection(list[y], mob, savetofile));
}

Promise.all(promises)
   .then(dt => {
       finalresult.push(dt); //pushes all 3 objects one by one
       console.log(dt); //prints 3 objects one by one
       client.close();
       if (y == (collist.length)) { 
           resolve(finalresult);
       }
   }); // <-- this will be raised once all your promises are resolved

我看到您在每个承诺中关闭客户端,并且该客户端不是局部变量.所以我认为你应该在完成所有承诺后关闭它.

I see you're closing client inside each promise and this client is not a local variable. So I think you should be closing it after all your promises are completed.

这篇关于for 循环内的 Node js promise 总是打印 Promise { &lt;pending&gt;}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆