我能想到的最佳用例是缓存AJAX响应。这是RebeccaMurphey关于该主题的介绍性帖子
var cache = {};
function getData( val ){
// return either the cached value or jqXHR object wrapped Promise
return $.when(
cache[ val ] ||
$.ajax('/foo/', {
data: { value: val },
dataType: 'json',
success: function( resp ){
cache[ val ] = resp;
}
})
);
}
getData('foo').then(function(resp){
// do something with the response, which may
// or may not have been retrieved using an
// XHR request.
});
基本上,如果该值在从缓存立即返回之前已经被请求一次。否则,AJAX请求将获取数据并将其添加到缓存中。的$.when
/ .then
不关心任何的这一点; 您需要关心的就是使用响应,.then()
在两种情况下都将响应传递给处理程序。jQuery.when()
手柄的非无极/延迟作为一个已完成,立即执行任何.done()
或.then()
上链。
对于任务可能会异步执行或可能不会异步执行以及您希望从代码中抽象出该条件的情况,Deferreds非常适合。
使用$.when
助手的另一个真实示例:
$.when($.getJSON('/some/data/'), $.get('template.tpl')).then(function (data, tmpl) {
$(tmpl) // create a jQuery object out of the template
.tmpl(data) // compile it
.appendTo("#target"); // insert it into the DOM
});