2017-07-24 159 views
0

的API请求我走线槽某些阵列:的Node.js与HTTP请求循环

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

为每个阵列我做3嵌套请求 但现在我有我的索引索引有时是错误的问题。我认为我的循环比请求更快。我如何可以采取以下方式:

  • 开始for循环指数= 1
  • 进行API调用1索引1
  • 等待API调用1个响应
  • 进行API调用2索引1
  • 等待API调用2
  • 进行API调用3索引1
  • 等待的响应为API调用的响应3

  • 指数++

  • 进行API调用1指数2 ......

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

 
}); 
 

 
}); 
 

 

 
}); 
 

 

 
} 
 

 

 
});

+1

首先你有一个语法错误。请先解决。 – Aron

回答

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

好友。

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

如果你想1比要求2请求超过3请求

你必须做这样的

request(options1,function(){ 

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


}); 

和应用异步或承诺,而不是为循环。

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