取消 promise

2019-08-26  本文已影响0人  织雪纱奈
 return new Promise(()=>{}); 

然而这个方案有一个不那么明显的缺陷,那就是会造成潜在的内存泄露。

重写then,如果相等,那么不执行回调

(function() {
  var STOP_VALUE = {}//只要外界无法“===”这个对象就可以了
  var STOPPER_PROMISE = Promise.resolve(STOP_VALUE)

  Promise.prototype._then = Promise.prototype.then

  Promise.stop = function() {
    return STOPPER_PROMISE//不是每次返回一个新的Promise,可以节省内存
  }

  Promise.prototype.then = function(onResolved, onRejected) {
    return this._then(function(value) {
      return value === STOP_VALUE ? STOP_VALUE : onResolved(value)
    }, onRejected)
  }
}())

Promise.resolve(8).then(v => {
  console.log(v)
  return 9
}).then(v => {
  console.log(v)
  return Promise.stop()//较为明确的语义
}).catch(function(){// will never called but will be GCed
  console.log('catch')
}).then(function(){// will never called but will be GCed
  console.log('then')
})
上一篇 下一篇

猜你喜欢

热点阅读