【问题标题】:nodejs-async: return mysql query result in for loopnodejs-async:在for循环中返回mysql查询结果
【发布时间】:2017-10-07 10:13:00
【问题描述】:

我有三个操作要一个接一个地做

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

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

【问题讨论】:

    标签: mysql node.js express asynchronous


    【解决方案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

    【讨论】:

    • 但是哪里可以放isDone函数呢??我正在使用异步瀑布方法
    • @Jabaa 我更新了我的代码以阐明我的解决方案。这应该可以,但我没有测试它。
    • @Jabaa 我再次更新了我的答案。使用 async.parallel 有一个更好、更清洁、更高效的解决方案。这应该会让你朝着正确的方向前进。
    • 谢谢让我试试
    • @Jabaa 如果它适合你,请接受我的回答:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    相关资源
    最近更新 更多