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
?
No, it only works for the outer promise, the one returned by the
then
call. This needs to be rejected for thecatch
callback to be activated. To get this promise rejected, eitherapiAccountStatus(…)
must reject or thethen
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'treturn
ing them so that they will not chain. You have to do