2017-09-01 238 views
0

我使用請求庫通過API與其他服務器進行通信。但是現在我需要同時發送多個(10個或更多)POST請求,並且只有在所有響應都是正確的情況下才能進一步移動。通常語法看起來有點像這樣:Node.js請求 - 處理多個POST請求

var options = { 
url: "", 
method: "POST", 
header: {...}, 
body: {...} 
}; 

request(options, function(err,response,body) 
{ 
} 

但是現在我有一個對象數組而不是單個選項變量。有沒有辦法做到這一點?或者也許有另一個圖書館能夠處理這個問題。

編輯:

var arrayOfIds = []; 
const requests = []; 
for(var i in range){ 
    var options = {} // here goes all bodies and headers to send 
    requests.push(// push a request to array dynamically 
    request(options, function(err,response,body){ 
    if(!err && response.statusCode == 201){ 
     arrayOfIds.push(body.id); 
    } 
    })); 

Promise.all(requests) 
.then(function(res){ 
    console.log(arrayOfIds); // this is empty 
}); 
+0

可能的複製(https://stackoverflow.com/questions/44636542/loop-through-asynchronous-request) –

回答

1

有幾種方法來解決這個問題:

  • 異步庫,方法並行
  • Promise.all

要切換您的要求的承諾,另外使用request模塊 - request-promise 。在代碼它看起來像這樣:的[循環通過異步請求]

const request = require('request-promise'); 

// Note, you don't assign callback here 
const promises = [ 
    request.post({...}), 
    request.post({...}), 
    request.post({...}) 
]; 

// And then you simply do Promise.all 
Promise.all(promises).then(console.log); 
+0

感謝。這非常有幫助。而如果我不知道確切的請求數量?我應該使用常規循環來完成const promises數組嗎? – Jacek717

+0

只需動態填充它們,這不是問題。 – Lazyexpert

+0

最後一個問題:所有這些請求都應該發回給我一個我剛剛在另一臺服務器上創建的對象的ID。我創建了一個ID數組,並試圖填充它,如果一切都正確,則推送一個body.id值。然而,它不起作用,Promise.all後我只得到一個空數組。你知道如何解決它嗎?我編輯了我的初始代碼以向您展示所有內容 – Jacek717