Search code examples
javascriptgeneratorredux-saga

redux-saga: How to ignore one error and get other responses in parallel tasks?


Here is my code, fetch several reports in parallel :

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

   }
}

However, one or more report may doesn't exist, but it doesn't effect the result, the error could be ignored.

But when a 404 fetch happened, it enter the catch block, how can I get the other successsful responses ?


Solution

  • Descend your try-catch logic down into the anonymous function. That way you can define what to do each time a call fails. Here for example, I just return null on a fail here.

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