具有http请求

时间:2017-07-24 12:31:09

标签: javascript node.js asynchronous

对于api请求我通过一些数组:

'邮件',     '20 .03.2017 05:32',     '11 .07.2017 03:44',     '2',     '0',     '2',     '0',     '4',     “3”     '46']

为每个数组我做3个嵌套请求 但现在我遇到的问题是我的请求索引有时是错误的。我认为我的循环比请求更快。我怎样才能采取以下方式:

  • 开始循环索引= 1
  • 使用索引1
  • 进行api调用1
  • 等待api call 1回复
  • 使用索引1
  • 进行api调用2
  • 等待api call 2的响应
  • 使用索引1
  • 进行api调用3
  • 等待api call 3的响应

  • 指数++

  • 使用索引2进行api调用1 ......

for (var i = 1; i <= (csvData.length-1); i++){


var options = { method: 'GET',
  url: 'https://api.pipedrive.com/v1/persons/find',
  qs: 
   { term: csvData[i][0],
     start: '0',
     search_by_email: '1',
     api_token: '' },
  headers: 
   { 'postman-token': '',
     'cache-control': 'no-cache' } };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  
  var user = JSON.parse(body);
    console.log("-->User gefunden<--");
    console.log("-->User: "+user.data[0].name+"<--");


    var options = { method: 'GET',
  url: 'https://api.pipedrive.com/v1/deals/find',
  qs: 
   { term: user.data[0].name,
     api_token: '' },
  headers: 
   { 'postman-token': '',
     'cache-control': 'no-cache' } };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  var deal = JSON.parse(body);


var options = { method: 'PUT',
  url: 'https://api.pipedrive.com/v1/deals/'+deal.data[0].id,
  qs: { api_token: '' },
  headers: 
   { 'postman-token': '',
     'cache-control': 'no-cache',
     'content-type': 'application/json' },
  body: { stage_id: csvData[i-1][9]},
  json: true };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

});

});


});


}


});

4 个答案:

答案 0 :(得分:1)

您需要使用: -

async.eachOfSeries(coll,iteratee,callback)作为父循环和

async.eachSeries()作为子循环。

有关详细信息,请参阅async库:

https://caolan.github.io/async/docs.html#eachOfSeries

答案 1 :(得分:0)

您需要使用闭包How do JavaScript closures work?。在异步时,您无法保证值。

答案 2 :(得分:0)

使用Async libraryseries方法。

async.series(['mail', '20.03.2017 05:32', '11.07.2017 03:44', '2', '0', '2', '0', '4', '3', '46' ].map( elem => { 
  return done => { // Building an array of functions to pass to Async. They will be executed one after the other, when done() is called
       callYourApi( elem, result => done(null,result) ) // 1st argument = error, null == no error
  }
},
(err, results) => { // Global callback when all the calls are finished (or when an error occured in the chain)
  // results is now an array of all the "result" of every call
})

答案 3 :(得分:0)

巴迪。

首先,你所做的语法是错误的。

如果您想要1个请求而不是2个请求而不是3个请求

你必须这样做

request(options1,function(){

request(options2,function(){
  request(options3,function(){
      // callback here
      });
});


});

并应用async或promises而不是for循环。

检查节点中的异步或承诺。