I\'ve been reading about deferreds and promises in jQuery but I haven\'t used it yet.
I\'ve understood everything very well but the method pipe. I really didn\'t get wha
Basically, Deferred.pipe() is an asynchronous equivalent to $.map(). It projects new values from other values provided as input, but its purpose is to be used with continuations.
Let's start with an example that only requires $.each()
and issues an AJAX request that returns a simple object. For each property of this object, we want the form control whose id
attribute is the property's key to set its value to the property's value. We can write something like:
$.ajax("your/url", {
dataType: "json"
}).done(function(data) {
$.each(data, function(key, value) {
$("#" + key).val(value);
});
});
Now let's say we want to apply some function to the values before updating the form controls. If we do that locally, we only have to write:
$.ajax("your/url", {
dataType: "json"
}).done(function(data) {
$.each(data, function(key, value) {
// doSomethingWith() projects values synchronously, as map() does.
$("#" + key).val(doSomethingWith(value));
});
});
But what happens if doSomethingWith()
is not implemented client-side, but server-side through another web service? In that case, we want to chain the control flow into the second AJAX request, and only update the form controls when the second request has returned. Deferred.pipe()
makes that easy:
$.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);
});
});