我試圖鏈Q承諾不「那麼」,所以最終的鏈條是這樣的:鏈的承諾不使用「然後」帶Q庫
var foo = new Foo();
foo
.method1()
.method2()
.method3();
如何實現Foo的方法,使每一個一旦前一個承諾得到解決,就會被執行?
這個問題被標記爲this one的確切副本,但我試圖用Q lib而不是jQuery來實現。
我試圖鏈Q承諾不「那麼」,所以最終的鏈條是這樣的:鏈的承諾不使用「然後」帶Q庫
var foo = new Foo();
foo
.method1()
.method2()
.method3();
如何實現Foo的方法,使每一個一旦前一個承諾得到解決,就會被執行?
這個問題被標記爲this one的確切副本,但我試圖用Q lib而不是jQuery來實現。
我不知道你是否會用這個獲得任何東西。
我想你可以做這樣的事情:
function Foo() {
var self = this,
lastPromise = Promise.resolve();
var chainPromise = function(method) {
return function() {
var args = Array.prototype.slice.call(arguments))
lastPromise = lastPromise.then(function(){
return method.apply(self, args);
});
return self;
}
}
this.method1 = chainPromise(function() {
// do the method1 stuff
// return promise
});
this.method2 = chainPromise(function() {
// do the method2 stuff
// return promise
});
// etc...
}
回報'this'關鍵字在JavaScript – Mahi
除非美孚爲Q的擴展,'this'並未真正發揮作用。 'method1'返回的東西本身必須包含一個'method2',只有在'method1'解析後才能調用它自己。 – Brian