Node js承诺for循环内始终会打印Promise {<pending>}

时间:2020-04-29 03:24:18

标签: javascript node.js promise

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

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');
            });
        }
    });
}

我无法弄清楚如何让循环等到所有的Promise被解决或使代码同步然后才解决finalresult数组?我该怎么办?

1 个答案:

答案 0 :(得分:1)

这里您需要的是 $('.data').on('click', async function() { await axios .post('ajax/edit_groups/' + $(this).attr('data-id')) .then(function(response) { console.log('in: ', $(this).attr('data-id')); $('#editGroups').modal('show'); $('#id_group').val(response.data_group[0].id); $('#name').val(response.data_group[0].group_name); $('#desc').val(response.data_group[0].group_desc); $('#inputRole').val(response.data_group[0].role); }) .catch(function(error) { console.log(error); }); }); 。它会返回一个新的诺言,一旦所有通过的诺言得到解决,该诺言就会得到解决。

您可以尝试类似的操作:

Promise.all()

我看到您在每个promise中都关闭了客户端,并且该客户端不是局部变量。因此,我认为您应该在完成所有承诺后就关闭它。