jQuery的Deferred
系統的一個用途是使用$.when()
函數。它採用可變數量的Promise's and will do something when they all
決心(or when the first
reject`s)
所以,如果你想在兩個阿賈克斯JSON
查詢,比如,你可以做的工作:
var funkyPromise = $.getJSON('http://funky.json.service.com');
var awesomePromise = $.getJSON('http://awesome.json.service.com');
$.when(funkyPromise, awesomePromise).then(function() {
/* do something amazing with the two objects */
}, function() {
/* at least one of the services failed this time */
});
你可以用jQuery的Deferred
做的另一件事系統是從一個Deferred
通過另一使用方法pipe
最終使用它之前通過「鏈」中的數據,使數據管道:
$.getJSON('http://funky.json.service.com')
.pipe(funkytoFunkier);
}).done(function(funkyData) {
/* we now have a funkier version of what the web service gave us */
});
奇妙的異步和解耦。
但是,如果我想在兩個異步Promise
的使用$.when()
但我們沒有他們中的一個還沒有,因爲它會通過pipe
異步會發生什麼?
var funkyPromise = $.getJSON('http://funky.json.service.com');
var awesomePromise = $.getJSON('http://awesome.json.service.com');
// run "funky" through an asynchronous "pipe" to get "funkier"
//
// ... but ... how ??
$.when(funkyier, awesome).then(function() {
/* do something amazing with the two objects */
}, function() {
/* at least one of the services failed this time */
});
那麼中間部分呢?
- 它是非常明顯的,我只是看不到它?
- 是否有可能,但相當微妙和棘手的東西?
- 將一些新的「倒」相當於
pipe()
或$.when()
等等,使它更容易?
它是可以接受的巢穴這些延期電話? – DrColossos
@DrColossos:對於這個問題,我的頭繞過它,所以對於一些使用情況嵌套將是一個選項,也可能有用例,它不是我想要了解它沒有嵌套...如果可能的是( - : – hippietrail