How to find out which promise resolved with Promise.any? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to find out which promise resolved with Promise.any? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I was doing some batch IO with Promise.all, but eventually I hit a limit of open files by creating too many IO promises at once. So instead, I made an utility, that will run those promises in batches of 50 at most.

One solution is to divide the tasks in batches of fifty, and then do Promise.all on each batch. But smarter solution would be to cycle the promises as they resolve using Promise.any. Problem is, Promise.any only returns the result, and not which promise returned.

How to find out which resolved so that I can replace it in the batch with new unresolved one?

Answer

There’s no native way to find the Promise that was completed.

But I thought of a workaround. Basically, I assigned each Promise an id then I destructure the return value of the Promise and log out the id and result

const Promise4 = fetch('https://pokeapi.co/api/v2/ability/?limit=1&offset=20').then(response => response.json()).then(result => ({
  id: 4,
  result
}));
const Promise1 = fetch('https://pokeapi.co/api/v2/ability/?limit=1&offset=12').then(response => response.json()).then(result => ({
  id: 1,
  result
}));
const Promise2 = fetch('https://pokeapi.co/api/v2/ability/?limit=1&offset=5').then(response => response.json()).then(result => ({
  id: 2,
  result
}));
const Promise3 = fetch('https://pokeapi.co/api/v2/ability/?limit=1&offset=23').then(response => response.json()).then(result => ({
  id: 3,
  result
}));


Promise.any([Promise1, Promise2, Promise3, Promise4]).then(({
  id,
  result
}) => console.log(`Promise${id} returned`, result.results[0].name));
We are here to answer your question about How to find out which promise resolved with Promise.any? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji