Skip to content Skip to sidebar Skip to footer

How Do I Break A Promise Chain?

How should I stop the promise chain in this case? Execute the code of second then only when the condition in the first then is true. var p = new Promise((resolve, reject) => {

Solution 1:

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

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

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

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

Solution 2:

You could move the chain into the conditional branch:

p.then((res) => {
  if(true) {
    returnPromise.resolve(res + 2).then((res) => {
      // executed only when the condition is true
    });
  } else {
    // do something // chain ends here
  }
});

Solution 3:

Just use something like: reject('rejected') in the else of the first task.

P
.then((res) => {
    if(true) {
        return res + 2
    } else {
        reject('rejected due to logic failure'    }
})
.then((res) => {
    // executed only when the condition is trueconsole.log(res)
})

Alternatively u can also add a catch section to ur first task with .catch() Hope this helps.

Post a Comment for "How Do I Break A Promise Chain?"