Chaining promises without using 'then'

前端 未结 4 2060
感动是毒
感动是毒 2020-12-19 21:12

I have an object (foo) that exposes several methods as promises (using jQuery deferred). The way I did it ended up with this kind of code:

var f         


        
4条回答
  •  轮回少年
    2020-12-19 21:56

    Create your own promise.

    function MyPromise(resolver) {
      var _promise = new Promise(resolver);
      this.then = function(onFulfilled, onRejected) {
        var _p = _promise.then(onFulfilled, onRejected);
        return new MyPromise(_p.then.bind(_p));
      };
    }
    

    Add whatever methods you want...

    MyPromise.prototype.doSomething = function() {
      return this.then(/*...*/);
    };
    

    voila!

    new MyPromise()
      .then(/*...*/).doSomething()
      .then(/*...*/).doSomething(); // etc...
    

    Bonus:

    ['resolve', 'reject', 'all'].forEach(function(method) {
      MyPromise[method] = function(...args) {
        var promise = Promise[method](...args);
        return new MyPromise(promise.then.bind(promise));
      };
    });
    

    Also in ES6:

    class MyPromise {
      constructor(resolver) {
        var _promise = new Promise(resolver);
        this.then = function(onFulfilled, onRejected) {
          var _p = _promise.then(onFulfilled, onRejected);
          return new MyPromise(_p.then.bind(_p));
        };
      }
      doSomething() {
        return this.then(/*...*/);
      }
    }
    

提交回复
热议问题