Chaining promises without using 'then'

前端 未结 4 2079
感动是毒
感动是毒 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:33

    Yes sure, you just need to extend your Deferreds to have these methods:

    function MyRpc { // if you can use ES2015 - this should be a `class`
      this._deferred = new $.Deferred();
    }
    // teach it to be a promise
    MyRpc.prototype.then = function(onFulfilled, onRejected) {
      return this._deferred.then(onFulfilled, onRejected);
    };
    
    // teach it to be a deferred
    MyRpc.protototype.resolve = function(arg) {
      this._deferred.resolve(arg);
    };
    
    MyRpc.prototype.reject = function(arg) {
      this._deferred.reject(arg);
    };
    
    // define your methods!
    
    MyRpc.prototype.method1 = function(arg) {
      var p = this._deferred.then(function(value) {
        // logic of `method1` from foo.method1 here
      });
      var rpc = new MyRpc(); // our continuation;
      p.then(function(v) { rpc.resolve(v) }, function(e) { rpc.reject(e); });
      return rpc;
    };
    

    Of course, with a real promise library all this is a lot easier than with jQuery's minimal promises.

    This would let you do:

    var rpc = new MyRpc();
    rpc.method1(1).method1(2).method1(3); // can also `.then` here
    

    I'm not sure it's worth it, but it works.

提交回复
热议问题