我有一個空的文檔數組。如何獲得可變數量的藍鳥承諾? (Nodejs)
let arrayOfDocuments = [];
我想打電話給HTTP請求(將SuperAgent)下載一個文本文件,並把它的內容到我的arrayOfDocuments。
request.get('docs.google.com/document/d/SOME_FILE_NAME').then((res) => {
arrayOfDocuments.push(res.text);
});
這部分我得到,但這裏是棘手的部分。我想把它放在for循環中並在for循環之後執行一些操作。因此,像:
for (let i = 0; i < numOfLinks; i++) {
// send the http requests as above
}
//do stuff here but only after the above for loop is finished.
如何只能做最後一行,如果循環結束?我的程序現在運行的方式,for循環之後的代碼在http請求得到響應並完成之前運行。我認爲有一種方法可以使用藍鳥諾言做到這一點,但我不確定。謝謝!
var promises = []
var links = ['a.com/a', 'a.com/b']
for (let i = 0; i < links.length; i++) {
promises.push(request.get(links[i])
}
Promise.all(promises).then(function(allRes) {
//do anything you want with allRes or iterate
for (var promise in promises){
promise.then(function(singleRes){/*do something with each promise after all resolve*/}
}
});
我認爲你正在尋找[ 'Promise.all'](http://bluebirdjs.com/docs/api/promise.all.html)。 –
我如何獲得發送的每個請求的回覆? – user3835653