Node.js - foreach里面的mysql查询

时间:2015-10-02 22:02:03

标签: javascript mysql node.js

我有这种代码结构:

connection.query(query1,function(err,rows) {
    var response = [];
    //doing something with rows
    rows.forEach(function(item) {
        connection.query(queryItem,function(err,rows) {
            //doing something
            result = rows[0].field;
            //and want to push it to an array
            response.push(result);
        });
    });
    console.log(response); //empty
});

我知道forEach正在阻止,但查询是非阻塞的。我试图使用承诺:

connection.query(query1,function(err,rows) {
    var response = [];
    //doing something with rows
    rows.forEach(function(item) {
        var promise = new Promise(function(resolve,reject) {
            connection.query(queryItem,function(err,rows) {
                //doing something
                result = rows[0].field;
                //and want to push it to an array
                resolve(result);
            });
        });
        promise.then(function(result) {
            console.log(result); //ok
            response.push(result) //not ok, result is empty
        });
    });
    console.log(response); //empty
});

但它没有帮助。如何将值从非阻塞函数推入数组并在之后使用?

1 个答案:

答案 0 :(得分:2)

创建promises是朝着正确方向迈出的一步,但是你需要更进一步,将promises聚合到一个数组中并传递给Promise.all,然后在尝试访问之前等待它们全部完成{{ 1}}。

response