jQuery 的一次使用 Deferred
系统带有 $.when()
功能。它需要可变数量 Promise's and will do something when they all
解决(or when the first
拒绝。)
所以如果你想对两个Ajax进行操作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 */
});
一切都非常异步和解耦。
但是如果我想使用 $.when()
会发生什么?关于两个异步Promise
但我们还没有其中之一,因为它将通过 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()
等等让它变得更容易?
最佳答案
pipe()返回一个新的 promise ,该 promise 将在管道解析时得到解决,因此您只需编写:
var funkyPromise = $.getJSON('http://funky.json.service.com');
var awesomePromise = $.getJSON('http://awesome.json.service.com');
$.when(funkyPromise.pipe(funkytoFunkier), awesomePromise).then(function() {
/* do something amazing with the two objects */
}, function() {
/* at least one of the services failed this time */
});
请注意,从 jQuery 1.8 开始,then()
与 pipe()
执行相同的操作,因此这两种方法基本上可以互换。
关于jQuery $.when() 其中一个参数来自异步 "Deferred pipe",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12282309/