Will outermost .catch() work for all chained / nes

2019-03-05 21:15发布

问题:

I have a bit of a long login process that relies on 3 api calls that looks like this at the moment:

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

As you can see this function is quiet verbose, but each nested api call relies on data returned from previous and I am trying to clean this up as much as possible (dispatch bits are redux specific, but these essentially fire whatever is passed in). At the end you will see a catch statement, my question is will this catch statement work for all of the promisses or only apiAccountStatus?

回答1:

At the end you will see a catch statement, my question is will this catch statement work for all of the promises?

No, it only works for the outer promise, the one returned by the then call. This needs to be rejected for the catch callback to be activated. To get this promise rejected, either apiAccountStatus(…) must reject or the then callback must throw an exception or return a promise that will be rejected.

This last thing is what you were missing - you were creating more promises inside that then callback, but you weren't returning them so that they will not chain. You have to do

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