【问题标题】:Promise.all not waiting for final resultPromise.all 不等待最终结果
【发布时间】:2021-07-22 22:31:58
【问题描述】:

目前我在处理承诺时遇到了一个小问题。基本上我有一个嵌套的地图,里面有一个获取请求。我得到的结果是正确的,但是我想要一个加载状态,需要知道请求何时结束。目前我的实现如下:

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

由于国家依赖于市场,我不知道如何才能等待一切完成,因为承诺在国家地图中,我无法脱离它,因为它依赖于它。

有什么帮助吗?

尝试添加 Promise.resolve() 并返回一组承诺并再次执行 promise.all,但这些承诺也从未解决。

任何帮助都会很好,非常感谢! :)

【问题讨论】:

  • countries.map(async c => …) 已经确实返回了一组承诺。只需在上面使用Promise.all。没有Promise.resolve() 调用,没有返回一组承诺。

标签: javascript async-await


【解决方案1】:

您错过了国家层面的承诺。如果您返回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
});

【讨论】:

  • 似乎它工作得很好,还有一件事,如果承诺失败,我想继续代码,我不在乎,事情是当承诺失败时它会停止执行,我不要成功
  • 如果获取失败,我就达不到 Promise.all(prCountries) :(
猜你喜欢
  • 2019-06-22
  • 1970-01-01
  • 2021-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 2020-11-01
  • 2020-06-23
相关资源
最近更新 更多