redux-saga:如何在并行任务中忽略一个错误并获得其他响应?
redux-saga: How to ignore one error and get other responses in parallel tasks?
这是我的代码,并行获取多个报告:
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 fetch发生时,它进入了catch块,我怎样才能得到其他成功的响应?
将您的 try-catch 逻辑下放到匿名函数中。这样你就可以定义每次调用失败时要做什么。例如,我在这里 return 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;
}
}));
}
发生这种情况是因为您没有处理 Promise 本身的错误。
您只需要在 fetchSingleReportRequest
内的 axios
请求中添加一个 catch
块。
例如,您可以这样写:
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) {
}
}
这是我的代码,并行获取多个报告:
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 fetch发生时,它进入了catch块,我怎样才能得到其他成功的响应?
将您的 try-catch 逻辑下放到匿名函数中。这样你就可以定义每次调用失败时要做什么。例如,我在这里 return 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;
}
}));
}
发生这种情况是因为您没有处理 Promise 本身的错误。
您只需要在 fetchSingleReportRequest
内的 axios
请求中添加一个 catch
块。
例如,您可以这样写:
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) {
}
}