2017-05-09 188 views
0

我有三个操作做彼此的NodeJS-异步:返回MySQL查询结果为循环

1.Fetch之后,从DB

2.Another MySQL查询一些行的for循环用于获取的一些数据和存储在变量

3.显示数据

对于我使用asyncwaterfall方法。

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不会因为第二个查询(在for循环是异步查询)

回答

1

你意识到手头的问题包含user结果。你的回调基本上必须等待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

+0

但是,在可以把'isDone'功能?我正在使用异步瀑布方法 – Jabaa

+0

@Jabaa我更新了我的代码以阐明我的解决方案。这应该工作,但我没有测试它。 – jpschack

+0

@Jabaa我再次更新了我的答案。使用async.parallel可以提供更好,更清洁,更高效的解决方案。这应该让你朝正确的方向发展。 – jpschack