小编典典

最外部的.catch()是否可用于所有链式/嵌套的promiss?

reactjs

我的登录过程有些长,目前依赖3个api调用:

export const authenticationSignIn = (email, password) =>
  (dispatch) => {
    dispatch({ type: AUTHENTICATION_REQUEST });
    apiAccountStatus(email, password)
    .then(({ data }) => {
      const status = data.status;
      if (status === 'ACCOUNT_CREATED') {
        apiSignIn(email, password)
        .then(({ data: sessionData }) => {
          apiIndexAccounts()
          .then(({ data: accountsData }) => {
            dispatch({ type: AUTHENTICATION_SUCCESS });
            window.router.transitionTo('/dashboard/home');
          });
        });
      } else if (status === 'SOMETHING ELSE') {
        // TODO: HANDLE SOMETHING ELSE
      }
    })
    .catch(({ response }) => {
      dispatch({ type: AUTHENTICATION_FAILURE });
      dispatch(notificationShow('ERROR', response.data.type));
    });
  };

如您所见,此函数非常详细,但是每个嵌套api调用均依赖于先前返回的数据,我正在尝试尽可能多地清除此数据(调度位是redux特有的,但是这些本质上触发了传入的任何内容)。最后,您会看到一个catch声明,我的问题是,该catch声明是否适用于所有允诺apiAccountStatus


阅读 239

收藏
2020-07-22

共1个答案

小编典典

最后,您会看到一个catch语句,我的问题是,该catch语句是否能满足所有诺言?

不,它仅适用于外部承诺,即then调用返回的承诺。需要将其拒绝catch才能激活回调。要拒绝此承诺,apiAccountStatus(…)必须拒绝或then回调必须抛出异常或
返回将被拒绝的承诺

最后一件事就是您所缺少的-您在then回调中创建了更多的Promise ,但是您没有使用return它们,因此它们不会链接。你所要做的

export function authenticationSignIn(email, password) {
  return (dispatch) => {
    dispatch({ type: AUTHENTICATION_REQUEST });
    apiAccountStatus(email, password)
    .then(({data: {status}}) => {
      if (status === 'ACCOUNT_CREATED') {
        return apiSignIn(email, password)
//      ^^^^^^
        .then(({ data: sessionData }) => {
          return apiIndexAccounts()
//        ^^^^^^
          .then(({ data: accountsData }) => {
            dispatch({ type: AUTHENTICATION_SUCCESS });
            window.router.transitionTo('/dashboard/home');
          });
        });
      } else if (status === 'SOMETHING ELSE') {
        // TODO: HANDLE SOMETHING ELSE
      }
    })
    .catch(({ response }) => {
      dispatch({ type: AUTHENTICATION_FAILURE });
      dispatch(notificationShow('ERROR', response.data.type));
    });
  };
}
2020-07-22