Yes sure, you just need to extend your Deferred
s 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…