Understanding Deferred.pipe()

Diego picture Diego · Apr 20, 2012 · Viewed 10.8k times · Source

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 what it is.

Could some please help me to understand what it does and where could it be used?

I know there is a question titled exactly like this one (here) but its not the same. I'm asking for help to understand it and some example. The objective of the other question is to get why it doesn't work in a particular case.

Answer

Frédéric Hamidi picture Frédéric Hamidi · Apr 20, 2012

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);
    });
});