Filipe Costa
Filipe Costa

Reputation: 23

Promise.all not waiting for final result

Currently I am having a small issue when dealing with promises. Basicly I have a nested map where inside I have a fetch request. The results I am getting back are correct, but I want to have a loading state, need to know when the requests are over. Currently my implementation is as following:

const countries = ['de', 'pt', 'en']
const market = ['test1', 'test2']


countries.map(async c => {
  const promises = market.map(m => {
    return fetch(endpoint + '/' + c + '/' + m)
  })
  
  const results = await Promise.all(promises)
})

Since countries depend on the market, I don't know how I can wait everything to finish since the promises are inside the countries map and I can't dettach from it since it depends on it.

Any help on this?

Tried to add Promise.resolve() and return an array of promises and do promise.all again, but those promises are also never resolved.

Any help will be good, thanks a lot! :)

Upvotes: 0

Views: 612

Answers (1)

David784
David784

Reputation: 7464

You're missing the promises at the countries level. If you return the Promise.all and then do another Promise.all on the results of countries.map, that should help.

const countries = ['de', 'pt', 'en'];
const market = ['test1', 'test2'];

const prCountries = countries.map(c => {
  const promises = market.map(m => {
    return fetch(endpoint + '/' + c + '/' + m);
  });

  return Promise.all(promises);
});

Promise.all(prCountries).then(x=> {
  // do stuff when all promises have resolved
});

Upvotes: 1

Related Questions