How do I break a promise chain?

You could read the documentation, which says

Promise.then return a rejected Promise if the input function throws an error, or the input function returns a rejected Promise.

If you prefer, you could read the Promise A spec, in the section about then, where promise2 refers to the resulting promise:

If either onFulfilled or onRejected throws an exception e, promise2 must be rejected with e as the reason.)

If you prefer, you could read the excellent 2ality blog:

then() returns a new promise Q (created via the constructor of the receiver): If either of the reactions returns a value, Q is resolved with it. If either of the reactions throws an exception, Q is rejected with it.

You could read the brilliant YDKJS:

A thrown exception inside either the fulfillment or rejection handler of a then(..) call causes the next (chained) promise to be immediately rejected with that exception.


You can throw an Error in the else block, then catch it at the end of the promise chain:

var p = new Promise((resolve, reject) => {
    setTimeout(function() {
        resolve(1)
    }, 0);
});

p
.then((res) => {
    if(false) {
        return res + 2
    } else {
        // do something and break the chain here ???
      throw new Error('error');
    }
})
.then((res) => {
    // executed only when the condition is true
    console.log(res)
})
.catch(error => {
  console.log(error.message);
})

Demo - https://jsbin.com/ludoxifobe/edit?js,console

Tags:

Javascript