简体   繁体   English

Promise.all 不等待最终结果

[英]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.基本上我有一个嵌套的 map 里面我有一个获取请求。 The results I am getting back are correct, but I want to have a loading state, need to know when the requests are over.我得到的结果是正确的,但是我想加载 state,需要知道请求何时结束。 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.由于国家依赖于市场,我不知道我如何才能等待一切完成,因为承诺在 map 国家内部,我无法脱离它,因为它取决于它。

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.尝试添加 Promise.resolve() 并返回一系列承诺并再次执行 promise.all ,但这些承诺也从未得到解决。

Any help will be good, thanks a lot: :)任何帮助都会很好,非常感谢::)

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.如果您返回Promise.all然后对countries.map的结果执行另一个Promise.all ,那应该会有所帮助。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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