運行在一系列承諾陣列的最常見的方式是使用array.reduce
- 像這樣
var pages = linksArray.then(function (arr) {
var pArray = [];
return arr.reduce(function (promise, link) {
var ret = promise.then(function() {
return loader(link)
// the next 3 lines will ensure all links are processed - any failed links will resolve with a value == false
.catch(function(err) {
return false;
});
});
pArray.push(ret);
// next three lines log when each loader has finished
ret.then(function() {
console.log('finished', link);
});
return ret;
}, Promise.resolve())
.then(function() {
return Promise.all(pArray);
});
})
然後,您可以像這樣訪問
pages.then(function (data) {
// data is an array of results of loader
console.log(data);
}).catch(function(err) { // any errors should be logged here
console.log(err);
});
結果
它是如何工作的:簡單地說,每次調用loader
「等待」,直到先前的調用在執行之前解決爲止 - 每個加載器的有效承諾保存在一個數組中。一旦最後的加載程序解析,該Promise.all
返回一個承諾如果您需要知道如何工作array.reduce解析爲每個呼叫的值的數組loader
- 讀this
你這是什麼expect(需要?)'pages'將會是什麼,你期望(需要)作爲'.then'塊中的'data'嗎? –
@JaromandaX我有一個鏈接的數組,並希望得到每個對應的頁面中的字符串數組 –
@Jaromanda X朋友,它是如何工作,5分鐘後還沒有返回 –