2017-05-09 17 views
0

のために私はいくつかのデータを取得するためforloopでnodejs-非同期:リターンMySQLのクエリ結果ループ

デシベル2.Another mysqlのクエリから1 1.Fetch

別の後にいくつかの行を行うための3つの事業を展開しているし、変数

3.Displayにおける店舗データそのために

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

しかし、2番目のクエリ(forループ内のクエリが非同期である)

答えて

1

あなたは手で問題を実現しているためresult最後の問題は、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