Jitender
Jitender

Reputation: 7969

Use case of jquery Deferred

I was reading about Deferred method in jquery. I understood how does it work but don't know when to use it. Like in simple ajax function I can use .success method for callback

function customAjax() {
    $.ajax({
        type: 'GET',
        url: 'abc/blala'
    }).success(function () {
        //callback
    })
}

But I saw some places it is written like below given example. So I am not sure when to use deferred.

function customAjax() {
    var deferred = jQuery.Deferred();
    $.ajax({
        type: 'GET',
        url: 'abc/blala'
    }).success(function (reponse) {
        deferred.resolve(response);
    });
    return deferred.promise
}

Upvotes: 0

Views: 339

Answers (2)

jfriend00
jfriend00

Reputation: 708206

The general trend with promise development is to not use a Deferred object or Deferred constructor any more. In fact, the ES6 standard for promises does not even support such a thing because it simply isn't needed. There is always an alternative way to code things that does not create a Deferred object.

In your particular case with your customAjax method, you don't need it at all. Instead, you can just do this:

function customAjax() {
    return $.ajax({
        type: 'GET',
        url: 'abc/blala'
    }).then(function (result) {
        // process the result in any way here
        return processed result here
    });
}

customAjax().then(function(value) {
    // do something with value here
});

So, in your situation above, there is no need to create your own promise. You can just use the promise that $.ajax() already returns and just chain onto it and return it.

Note: I also changed your code to use .then() because that is the "standard" way of doing things and is already supported by jQuery. jQuery is moving to a much more standards-compatible promise implementation in jQuery 3.x so it's wise to start coding that way now.


If you do need to create your own promise in jQuery 1.x or 2.x and want to do it as compatible as possible with the ES6 standards, while still using the jQuery supported stuff, you can do something like this:

function delay(t) {
    return jQuery.Deferred(function(def) {
        setTimeout(function() {
            def.resolve();
        }, t)
    }).promise();
}

For reference purposes, the ES6 standards syntax would look like this:

function delay(t) {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            resolve();
        }, t)
    });
}

As for when to use what with $.ajax(), life is a bit confusing. $.ajax() supports a zillion different ways to get notified when it's done or when there's an error. There are straight callbacks passed as arguments. There's .success() (which is now deprecated). There's .done() which is promise-like, but non-standard. There's .then() which is almost standard.

In my opinion, there are huge advantages to using one and only method and making that method be the standard promise mechanism with .then(). This then allows you to have all the other advantages of using promises for async operations which include:

  1. The ability to chain multiple async operations together in a sequence.
  2. The ability to coordinate multiple async operations using things like $.when() or Promise.all().
  3. Throw safety even in async operations (this will require ES6 compatible promises in jQuery 3.x).
  4. Significantly enhanced error propagation, even from deeply nested async operations.
  5. A "standard" way to code async operations.

Upvotes: 1

ic3man7019
ic3man7019

Reputation: 711

A deferred object is something you would use to get the result of an asynchronous operation so that you can use it within the synchronous flow of the application, if that makes sense. Any results that are obtained asynchronously are not immediately available to be returned; rather, they are available sometime in the future. A deferred object allows you to access those results when they are available.

Upvotes: 1

Related Questions