How do I break a promise chain?

前端 未结 4 1474
北恋
北恋 2020-12-03 12:19

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((res         


        
相关标签:
4条回答
  • 2020-12-03 12:50

    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

    0 讨论(0)
  • 2020-12-03 12:50

    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 true
        console.log(res)
    })
    

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

    0 讨论(0)
  • 2020-12-03 12:51

    You could move the chain into the conditional branch:

    p.then((res) => {
      if(true) {
        return Promise.resolve(res + 2).then((res) => {
          // executed only when the condition is true
        });
      } else {
        // do something 
        // chain ends here
      }
    });
    
    0 讨论(0)
  • 2020-12-03 13:02

    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.

    0 讨论(0)
提交回复
热议问题