2016-09-07 5 views
0

配列[1,2,3,4]は2つを取り出して2つのリクエストを送信します。Nodejs以前のロジックが完了したときにロジックを実行する方法

完了したらもう2回、2つの新しいリクエストを作成します。

Nodejsが同期的なので、以下のように私はそれを行うことができません。

var request = require('request'); 
var args=[1,2,3,4]; 
function chunk(){...} 
args = chunk(args,2); //My custom function to split array into chunks 

args.forEach(function(value) 
{ 
    value.forEach(function(value_value) 
    { 
     /***********sent requests**************/ 
     var options = { 
      method: 'POST', 
      url: 'http://dev.site/date.php', 
      formData: {arguments:value_value} 
     }; 
     request(options, function (error, response, body) 
     { 
      if (body=='hello') { 
       console.log(body); 
      } 
     }); 
     /**************************************/ 
    }); 
}); 

あなたがrequest-promiseqを使用することができます私に

+0

あなたはサードパーティのモジュールを使いたいと思うので、 'lodash'の' chunk'をお勧めします:http://devdocs.io/lodash~4/index#chunk リクエストを順番に行うために、一度、 'eachSeries'関数で' async'のようなモジュールを調べることをお勧めします:http://caolan.github.io/async/docs.html#.eachSeries – forrert

+0

速い答えのためのthx私は正確に説明していません私はいくつかのロジックを待ってから次のステップに進む必要があります –

答えて

0

を助けてください - そして、チェーンの応答:

var request = require('request-promise'); 
var Q = require('q'); 
var args=[1,2,3,4]; 

function chunk(){...} 
args = chunk(args,2); //My custom function to split array into chunks 

args.forEach(function(value) 
{ 
    var result = Q(); 
    args.forEach(function (t) { 
     result = result.then(request_each.bind(null, value)); 
    }); 
    return result; // result has the final promise (use .then on that) 
}); 

function request_each(value) { 
    return Q.all(value.forEach(function(value_value) 
    { 
     /***********sent requests**************/ 
     var options = { 
      method: 'POST', 
      url: 'http://dev.site/date.php', 
      formData: {arguments:value_value} 
     }; 

     return request(options);   
     /**************************************/ 
    })); 
} 

あなただけ(request_each機能の変更)qrequestを使用することができます。

function request_each(value) { 
    return Q.all(value.forEach(function(value_value) 
    { 
     var deferred = Q.defer(); 
     /***********sent requests**************/ 
     var options = { 
      method: 'POST', 
      url: 'http://dev.site/date.php', 
      formData: {arguments:value_value} 
     }; 

     request(options, function (error, response, body) { 
      if (body=='hello') { 
       deferred.resolve(body); 
      } 
     }); 
     return deferred.promise;   
     /**************************************/ 
    })); 
} 
関連する問題