我有一个对象 (foo
),它公开了几个方法作为 promise (使用 jQuery deferred)。我这样做的方式最终得到了这种代码:
var foo = createNewFoo();
$.when(foo.method1(arg))
.then(foo.method2)
.then(foo.method3);
我希望将下面的代码重构得更好,看起来像这样:
var foo = createNewFoo()
.method1(arg)
.method2()
.method3();
但我不确定如何实现 foo
这可能。
最佳答案
当然可以,您只需要扩展您的 Deferred
即可拥有这些方法:
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;
};
当然,使用真正的 promise 库比使用 jQuery 的 minimal promise 所有这一切都很多。
这会让你做:
var rpc = new MyRpc();
rpc.method1(1).method1(2).method1(3); // can also `.then` here
我不确定这是否值得,但它确实有效。
关于javascript - 不使用 'then' 链接 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35774777/