2

I am trying to break the promise chain by not returning a promise at one of the intermediary steps.

identity
.token(username, password)
})
.then((response) => {
  // Here I would like to break the promise chain.. HELP please..
  if (!token.tfa || !allow2FA)
    return res.status(200).json(token.raw);

  return twoFactor.generateLoginOtc(username, token);
})
.then((response) => {
  return res.status(204).json();
})
.catch((error) => {
  console.log(error);
  return res.status(error.status).json(error);
});
Gabriel
  • 741
  • 2
  • 9
  • 18

2 Answers2

3

You can't break promise chains in a nice way, but you can nest them:

identity.token(username, password).then(response => {
  if (!token.tfa || !allow2FA) {
    return res.status(200).json(token.raw);
  }
  return twoFactor.generateLoginOtc(username, token).then(response => {
    return res.status(204).json();
  })
}).catch(error => {
  console.log(error);
  return res.status(error.status).json(error);
});
robertklep
  • 198,204
  • 35
  • 394
  • 381
0

To break a promise chain, instead of returning, you need to throw something - usually an error.

.then((response) => {
  if (!token.tfa || !allow2FA) {
    res.status(200).json(token.raw);

    // throw error here
    throw new Error('Error message');
  }

  return twoFactor.generateLoginOtc(username, token);
})
.then((response) => {
  return res.status(204).json();
})
.catch((error) => {
  console.log(error);
  return res.status(error.status).json(error);
});
Aron
  • 8,696
  • 6
  • 33
  • 59
  • 1
    No. That would still write two resposes. – Bergi May 23 '17 at 09:23
  • In this code yes it would write both the response in the first `then` and also the response in the `catch`. If OP doesn't want to do that then obviously one of those needs to be removed. – Aron May 23 '17 at 09:26
  • Thanks for your answer, but I am going to accept the first answer. I don't want to throw an error as it isn't one. – Gabriel May 23 '17 at 09:35
  • @Aron No, he does want both the write when the token fails and the write when an error happens in the `token()` or `generateLoginOtc()` methods. – Bergi May 23 '17 at 09:38