【问题标题】:Rejecting from Promise.all拒绝 Promise.all
【发布时间】:2020-11-17 20:26:18
【问题描述】:

我有一个 aysnc 函数,它获取数据并返回 Promise.all 的值,即

const fetchDownloadMenuData = async selectedItems => {
return Promise.all(
  selectedItems.map(async item => {
    try {
      if (item.id === 'interviewGuide') {
        const interviewGuide = await positionCandidatesService.getCandidate(
          positionId,
          candidateSelected.id
        );
        return interviewGuide.interviewGuide;
      }

      if (item.id !== 'overview' && item.id !== 'profile') {
        const outcome = await outcomesService.get(candidateSelected.id, item.id);
        return outcome;
      }
      return null;
    } catch (err) {
      appInsights.trackException({
        error: new Error(`Error fetching candidate outcome: ${JSON.stringify(err)}`)
      });
      return null;
    }
  })
  )};

我这样称呼这个函数:

 try {
  downloadData = await fetchDownloadMenuData(selectedItems);
} catch (err) {
  appInsights.trackException({
    error: new Error(`Could not fetch all PDF data: ${JSON.stringify(err)}`)
  });
  return;
}

但它永远不会被捕获。为什么是这样?如果所有的承诺都没有解决,我如何让它拒绝?

谢谢

【问题讨论】:

  • 我相信你的收获,你应该像这样拒绝 Promise:Promise.reject() 否则它会解决它

标签: reactjs async-await es6-promise promise.all


【解决方案1】:

您没有拒绝map...catch block,而是返回null。这就是Promise.all 无法捕获异常的原因。您需要在 catch 块中使用throw,记住,throw 将终止执行流程。

这样试试

selectedItems.map(async item => {
    try {
       ...async stuff
    } catch (err) {
      appInsights.trackException({
        error: new Error(`Error fetching candidate outcome: ${JSON.stringify(err)}`)
      });
      throw err OR throw new Error(err) <-- this is missing earlier.
    }
  })

【讨论】:

    猜你喜欢
    • 2018-06-08
    • 2021-08-13
    • 2019-10-13
    • 2019-04-25
    • 2017-06-19
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    相关资源
    最近更新 更多