nodejs-async:在for循环中返回mysql查询结果

时间:2017-05-09 07:46:55

标签: mysql node.js express asynchronous

我有三个操作要一个接一个地进行

1.从db

中获取一些行

2. forloop中的另一个mysql查询,用于获取一些数据并存储在变量

3.显示数据

我正在使用async waterfall方法。

async.waterfall([
            function(callback){
                //first sql and pass the result to second function
                collection.getAllCollections(function (status,error,result) {
                    callback(null,result);
                });
            },
           //running another query in loop with result with previous
            function(result, callback){
                for(var i=0;i<result.length;i++){
                    collection.getImages(result[i].id,function (status,error,user) {
                        //append the query result to old result
                         result[i]['users'] = user;
                    });
                }
                callback(null,result);
            }
        ], function (err, result) {

            console.log("result",result);
        });

但问题final result不包含user结果,因为第二个查询(for循环中的查询是异步的)

1 个答案:

答案 0 :(得分:1)

你意识到了手头的问题。你的回调基本上必须等待for循环结束。 例如:

async.waterfall([
    function(next){
        //first sql and pass the result to second function
        collection.getAllCollections(function (status,error,result) {
            next(null, result);
        });
    },
    function(result, next){
        var calls = [];

        //putting every call in an array
        result.forEach(function(resultObject){
            calls.push(function(callback) {
                collection.getImages(resultObject.id, function (status, error, user) {
                     resultObject['users'] = user;
                     callback(null, resultObject);
                });
            }
        )});

        //performing calls async parallel to each other
        async.parallel(calls, function(err, results) {
            //executed as soon as all calls are finished
            if (err) {
                next(err, null);
            } else {
                next(null, results);
            }
        });
    }
], function (err, result) {

    console.log("result",result);
});

文档:http://caolan.github.io/async/docs.html#parallel