redux-saga:如何在并行任务中忽略一个错误并获得其他响应?

时间:2018-07-25 07:12:39

标签: redux-saga

这是我的代码,并行获取多个报告:

function fetchSingleReportRequest(reportId) {
   return axios.get(`/api/${reportId}`)
}

function* fetchReportsInfo({payload: {data: reportIds}}) {
   try {
     const responses = yield all(reportIds.map(reportId => 
      call(fetchSingleReportRequest, reportId)))
   } catch (e) {

   }
}

但是,一个或多个报告可能不存在,但不影响结果,该错误可以忽略。

但是当发生404提取时,它进入catch块,我如何获得其他成功的响应?

2 个答案:

答案 0 :(得分:1)

发生这种情况是因为您没有在Promise本身中处理错误。

您只需要在catch内的axios请求中添加一个fetchSingleReportRequest块。

例如,您可以编写如下内容:

function fetchSingleReportRequest(reportId) {
   return axios.get(`/api/${reportId}`)
     .catch(() => {
       return null
     })
}

function* fetchReportsInfo({payload: {data: reportIds}}) {
   try {
     let responses = yield all(reportIds.map(reportId => 
      call(fetchSingleReportRequest, reportId)))
     responses = responses.filter((res) => res !== null)
   } catch (e) {

   }
}

答案 1 :(得分:0)

将您的try-catch逻辑下降到匿名函数中。这样,您可以定义每次通话失败时该怎么办。例如,在这里,我只是在失败的情况下返回null

function fetchSingleReportRequest(reportId) {
   return axios.get(`/api/${reportId}`)
}

function* fetchReportsInfo({payload: {data: reportIds}}) {
  const responses = yield all(reportIds.map(reportId => {
    try {
      return call(fetchSingleReportRequest, reportId)
    } catch (e) {
      return null;
    }
  }));
}