How to properly break out of a promise chain?

后端 未结 3 1369
忘了有多久
忘了有多久 2020-11-22 06:12

Based on the question here: jQuery chaining and cascading then's and when's and the accepted answer, I want to break the promise chain at a point but haven\'t yet fo

3条回答
  •  情歌与酒
    2020-11-22 06:38

    For folks using built-in browser promises and looking for a way to halt the promise chain without making all consumers know about the rejection case, triggering any chained then's or catches or throwing any Uncaught (in promise) errors, you can use the following:

    var noopPromise = {
      then: () => noopPromise, 
      catch: () => noopPromise
    }
    
    function haltPromiseChain(promise) {
      promise.catch(noop)
    
      return noopPromise
    }
    
    // Use it thus:
    var p = Promise.reject("some error")
    p = haltPromiseChain(p)
    p.catch(e => console.log(e)) // this never happens
    

    Basically, noopPromise is a basic stubbed out promise interface that takes chaining functions, but never executes any. This relies on the fact that apparently the browser uses duck-typing to determine if something is a promise, so YMMV (I tested this in Chrome 57.0.2987.98), but if that becomes a problem you could probably create an actual promise instance and neuter its then and catch methods.

提交回复
热议问题