简体   繁体   中英

Combining promises into promise.all

For a list of ids I'd like to make some GETs. 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). Since this happens in some kind of API controller, I rather not have to return the "ids" along with the promises. 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. See this example, that has strings instead of Promises so you can see the output by running the snippet:

 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, ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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