繁体   English   中英

将 promise 组合成 promise.all

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM