20

I am trying to implement the jQuery Deferred.pipe() method for the following scenario:

  1. Add a user in DB via $.ajax()
  2. Get response whether user was added correctly or not.
  3. If successfully added, get all the user list from server via $.ajax()
  4. Display the list via jQuery templates

This is something which I tried:

var addUserSuccess = function( data ) {
    if ( data.returnCode !== "success" ) {
        return $.Deferred().reject('Error saving user');
    }
    getUsers();
}

var addUser = function() {
    return $.ajax(url, {
        type: "POST",
        data: { username: 'test' },
        contentType: "application/json",
        dataType: "json"
    });
}

var displayUsers = function( data ) {
    $('#myTmpl').tmpl(data.d).appendTo('#myDiv');
}

var getUsers = function () {
    return $.ajax(url, {
        type: "GET",
        data: {},
        contentType: "application/json",
        dataType: "json"
    });
}

$.when(addUser()).pipe(addUserSuccess).then(displayUsers)

But this does not work. I know there is something missing or wrong. Any help?

Ashish
  • 2,424
  • 6
  • 36
  • 52

1 Answers1

20

In addUsersSuccess, you should be returning getUsers. It's a simple typo, you got the main idea perfectly right and are using pipe as it should be and nicely :)

Julian Aubourg
  • 11,068
  • 1
  • 27
  • 28
  • Thanks for the reply and confirmation about the code. However, just wanted to confirm, can we call this code in a chained manner, something where we can chain all the request and callbacks in a single statement. Something like: `$.when(ajaxreq1).pipe(ajaxreq2).then(successcallback1).then(successcallback2)` This way we get to know from a single statement all the request and callbacks. – Ashish May 07 '11 at 17:05
  • @Ashish: yes, the Promises and Deferreds are completely chainable. You could event $.when(...).pipe(...).done(cb1).pipe(...).done(cb2), anything is possible ;) – Julian Aubourg May 08 '11 at 00:51
  • I tried something like this [http://jsfiddle.net/8AtbP/2/](http://jsfiddle.net/8AtbP/2/). But does not work. – Ashish May 08 '11 at 06:00