首页 > 解决方案 > 有没有更好的方法在捕获拒绝时链接异步 thunk?

问题描述

由于创建的 thunkcreateAsyncThunk 将始终返回已解决的 promise。有没有比unwrapResult每次都添加以捕获拒绝更好的方法来处理链接的重击?

const fetchUsers = createAsyncThunk('users/fetch', myService.fetchUsers);
const updateUser = createAsyncThunk('users/update', myService.updateUser);

export const updateAndFetch = values => async dispatch => {
  const result = await dispatch(updateUser(values));
  const unwrapped = unwrapResult(result); // required to see if first update was rejected
  return dispatch(fetchUsers());
}

标签: reduxredux-thunkredux-toolkit

解决方案


并不真地。

你也可以这样写

export const updateAndFetch = values => async dispatch => {
  const result = await dispatch(updateUser(values)).then(unwrapResult);
  return dispatch(fetchUsers());
}

或者

export const updateAndFetch = values => async dispatch => {
  const result = await dispatch(updateUser(values));
  if (updateUser.fulfilled.match(result)) {
    return dispatch(fetchUsers());
  }
}

但在某些时候你必须做那个检查。


推荐阅读