【问题标题】:Will outermost .catch() work for all chained / nested promisses?最外层的 .catch() 是否适用于所有链式/嵌套式 Promise?
【发布时间】:2017-04-03 07:46:38
【问题描述】:

我有一个很长的登录过程,它依赖于目前看起来像这样的 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 声明是否适用于所有的promises 或只适用于apiAccountStatus

【问题讨论】:

    标签: javascript api reactjs promise redux


    【解决方案1】:

    最后你会看到一个 catch 语句,我的问题是这个 catch 语句是否适用于所有的 Promise?

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

    这最后一件事是你所缺少的——你在 then 回调中创建了更多的承诺,但你没有 returning 他们这样他们就不会被链接。你必须这样做

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-11
      • 2018-02-18
      • 2018-10-01
      • 2016-02-17
      • 2019-09-29
      • 1970-01-01
      • 2023-01-12
      相关资源
      最近更新 更多