在不使用"then"的情况下链接promise [英] Chaining promises without using 'then'
本文介绍了在不使用"then"的情况下链接promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象(foo
),该对象公开了一些应许方法(使用延迟的JQuery).我这样做的方式最终得到了这样的代码:
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 foo = createNewFoo();
$.when(foo.method1(arg))
.then(foo.method2)
.then(foo.method3);
我希望将代码重构为更好的东西,例如:
I wish to refactor my code to something nicer, like this:
var foo = createNewFoo()
.method1(arg)
.method2()
.method3();
但是我不确定如何实现foo
,所以这是可能的.
But I'm not sure how to implement foo
so it would be possible.
推荐答案
是的,您只需要扩展Deferred
即可使用以下方法:
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;
};
当然,与真正的Promise库相比,这一切要比jQuery的最小Promise容易得多.
Of course, with a real promise library all this is a lot easier than with jQuery's minimal promises.
这可以让您做到:
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.
这篇关于在不使用"then"的情况下链接promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文