Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding jQuery Deferred.pipe()

Tags:

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?

like image 583
Ashish Avatar asked May 07 '11 13:05

Ashish


People also ask

What is deferred method in jQuery?

The Deferred object, introduced in jQuery 1.5, is a chainable utility object created by calling the jQuery. Deferred() method. It can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.

What is pipe in jQuery?

pipe() method in jQuery is used to add utility method to filter, chain Deferreds.

What is jQuery deferred and promise object?

A deferred object is an object that can create a promise and change its state to resolved or rejected . Deferreds are typically used if you write your own function and want to provide a promise to the calling code. You are the producer of the value. A promise is, as the name says, a promise about future value.


1 Answers

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 :)

like image 128
Julian Aubourg Avatar answered Oct 20 '22 01:10

Julian Aubourg