Gabriel Gabriel - 1 year ago 85
Node.js Question

Node.js break promise chain

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

Answer Source

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);
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download