即使 API 失败,我如何 运行 代码

How can I run the code even when API fails

我有一个调用 saga 的动作(我在其中进行 API 调用)。该动作在循环中被调用两次。

index.js



componentDidMount(){
        this.props.nameList.map((name) => { 
             this.props.actions.getDetails(this.props.store.requestBody[name], name);
        })
    }

action.js

export const getDetails= (data, name) => ({
    type: GET_DETAILS,
    ...{data, name}
})

saga.js

export function* getDetails({data, name}){
    try{
        const response = yield call(getDetailsApi, data);
        if (response) {
            yield put(setDetails({[name] : response.data}));
        }
    }
    catch(error){
        yield put(setDetails({[name] : ''}));
    }
}


export default function* rootSaga() {
    yield takeLatest(GET_DETAILS, getDetails);
}

我在这里尝试的是,如果尝试成功,则使用响应更新 reducer,如果失败,则使用“”更新 reducer(catch 块中的代码)。

问题是,如果两个 API 调用都失败(它们有时会失败),则 catch() 仅被调用一次(第一个 API 调用失败)。

每次 API 失败时如何更新我的减速器?

看起来问题是由助手 fn takeLatest() 引起的。将其更改为 takeEvery() 对我有用。

Unlike takeEvery, takeLatest allows only one fetchData task to run at any moment. And it will be the latest started task. If a previous task is still running when another fetchData task is started, the previous task will be automatically cancelled.