2016-11-19 37 views
0

我有一点长登录过程,它依赖于3个API调用,看起来像这样的时刻:最外层的.catch()适用于所有链接/嵌套promisses吗?

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调用依赖于数据从前一个返回,我试图尽可能清理它(调度位是特定的,但这些基本上是火的任何传递)。最后你会看到一条catch声明,我的问题是这个声明是否适用于所有的promisses或只有apiAccountStatus

回答

2

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

不,它仅适用于外的承诺,由then调用返回的一个。这需要被拒绝,catch回调被激活。为了得到这个承诺被拒绝,要么apiAccountStatus(…)必须拒绝,要么then回调必须抛出异常或返回承诺,将被拒绝

这最后一件事是你错过了 - 你在then回调中创造了更多的承诺,但你不是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)); 
    }); 
    }; 
}