简体   繁体   English

将 promise 组合成 promise.all

[英]Combining promises into promise.all

For a list of ids I'd like to make some GETs.对于 ID 列表,我想做一些 GET。 These are wrapped in a promise.这些都包裹在一个承诺中。

let ids = [1, 2, 3]
let promises = [];
for (id in ids) {
    promises.push(ApiService.get(url + id))
}
return promises

Now when calling promises.all on the result, the results are in order of creating them (1, 2, 3).现在,当对结果调用 promises.all 时,结果按创建它们的顺序排列 (1, 2, 3)。 Since this happens in some kind of API controller, I rather not have to return the "ids" along with the promises.由于这种情况发生在某种 API 控制器中,我宁愿不必将“ids”与承诺一起返回。 But rather return something of a:而是返回一些东西:

{1: PromiseofId1, 2: PromiseofId2, 3:PromiseofId3}

Maybe my way of thinking is flawed, I am open for suggestions.也许我的思维方式有缺陷,我愿意接受建议。

Since you know the order, you can reassociate them afterwards.由于您知道顺序,因此您可以在之后重新关联它们。

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;
});

You can use reduce to build an object that maps each id into a Promise object.您可以使用reduce构建一个将每个 id 映射到Promise对象的对象。 See this example, that has strings instead of Promises so you can see the output by running the snippet:请参阅此示例,其中包含字符串而不是 Promises,因此您可以通过运行代码片段来查看输出:

 let ids = [1, 2, 3] let promises = ids.reduce((acc, cur) => ({...acc, [cur]: `ApiService${cur}`}), {}); console.log(promises);

In your case, you can have this:在你的情况下,你可以这样:

let ids = [1, 2, 3]
let promises = ids.reduce((acc, cur) => ({ ...acc, [cur]: ApiService.get(url + id)}), {});

You might want something like this.你可能想要这样的东西。

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