基本上,延迟.pipe() http://api.jquery.com/deferred.pipe/是一个异步等价于$.map() http://api.jquery.com/jQuery.map/。它从作为输入提供的其他值中投影出新值,但其目的是与延续一起使用。
让我们从一个例子开始,只需要$.each()
并发出返回一个简单对象的 AJAX 请求。对于该对象的每个属性,我们希望表单控件的id
attribute 是属性的键,用于将其值设置为属性的值。我们可以这样写:
$.ajax("your/url", {
dataType: "json"
}).done(function(data) {
$.each(data, function(key, value) {
$("#" + key).val(value);
});
});
现在假设我们要在更新表单控件之前对这些值应用一些函数。如果我们在本地这样做,我们只需要编写:
$.ajax("your/url", {
dataType: "json"
}).done(function(data) {
$.each(data, function(key, value) {
// doSomethingWith() projects values synchronously, as map() does.
$("#" + key).val(doSomethingWith(value));
});
});
但如果发生什么情况doSomethingWith()
不是在客户端实现的,而是通过另一个Web服务在服务器端实现的?在这种情况下,我们希望将控制流链接到第二个 AJAX 请求中,并且仅在第二个请求返回时更新表单控件。Deferred.pipe()
让这变得容易:
$.ajax("your/url", {
dataType: "json"
}).pipe(function(theOriginalData) {
return $.ajax("your/web/service/doSomethingWith", {
data: theOriginalData,
dataType: "json"
});
}).done(function(theFinalData) {
$.each(theFinalData, function(key, value) {
$("#" + key).val(value);
});
});