[英]Combining promises into promise.all
對於 ID 列表,我想做一些 GET。 這些都包裹在一個承諾中。
let ids = [1, 2, 3]
let promises = [];
for (id in ids) {
promises.push(ApiService.get(url + id))
}
return promises
現在,當對結果調用 promises.all 時,結果按創建它們的順序排列 (1, 2, 3)。 由於這種情況發生在某種 API 控制器中,我寧願不必將“ids”與承諾一起返回。 而是返回一些東西:
{1: PromiseofId1, 2: PromiseofId2, 3:PromiseofId3}
也許我的思維方式有缺陷,我願意接受建議。
由於您知道順序,因此您可以在之后重新關聯它們。
let ids = [1, 2, 3]
let promises = [];
for (id in ids) {
promises.push(ApiService.get(url + id))
}
Promise.all(promises).then(results => {
const data = {};
results.forEach( (value, index) => { data[ ids[index] ] = value } );
return data;
});
您可以使用reduce
構建一個將每個 id 映射到Promise
對象的對象。 請參閱此示例,其中包含字符串而不是 Promises,因此您可以通過運行代碼片段來查看輸出:
let ids = [1, 2, 3] let promises = ids.reduce((acc, cur) => ({...acc, [cur]: `ApiService${cur}`}), {}); console.log(promises);
在你的情況下,你可以這樣:
let ids = [1, 2, 3]
let promises = ids.reduce((acc, cur) => ({ ...acc, [cur]: ApiService.get(url + id)}), {});
你可能想要這樣的東西。
async function getData(){
const ids = [1, 2, 3]
const promises = ids.map(id => ApiService.get(url + id))
const responses = await Promise.all(promises)
// Read whatever data from the response
return responses.reduce((accumulator, response, index) => {
accumulator[index + 1] = response.data
}, {})
}
// Call it from an async function like this.
const dataMap = await getData()
// Returns {1:data1, 2:data2, ... }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.