Question

I am curious if I am using the deferred incorrectly and if not - is there a more eloquent way. So, I am firing this ajax request multiple times during a persons page view. Now, I understand I can only resolve the deffered once, so I reset the "def" appropriately. But I am wondering if I can assign the ajax call to the variable, and pass in the unique identifier and resolve the deferred?

I need things to happen either on the success or error of the ajax request.

So, I have an ajax request.

// some code. I set some var.

  var def = $.Deferred();

// more code

  $.ajax({
        dataType: "json",
        url: url,
        data: params,
        success: function(d) {
                     // resolve my deferred and pass a unique identifier
                        def.resolved('onSucc');
                 },
        error: function(d) {
                       def.resolved('onErr');
                    };

    });

To something like?

  var def = $.ajax({
        dataType: "json",
        url: url,
        data: params,
        success: function(d) {
                     // resolve my deferred and pass a unique identifier
                       return def.resolved('onSucc');
                 },
        error: function(d) {
                       return  def.resolved('onErr');
                    };

    });

Also, is there a need to return a promise here? My code seems to work ok without it - but I am curious if I am missing out.

Was it helpful?

Solution

You are actually not using deferred correctly. Deferred objects are for creating promise chains from scratch when making a non-promisified API promisified. The way you're using it is called the deferred anti pattern.

Promises chain, so instead of reverting to callbacks and deferred objects, you can simply use the chaining function then that transforms a promise into a new promise:

return $.ajax({
    dataType: "json",
    url: url,
    data: params,
}).then(function(result){
     console.log("got result!", result);
     return someTransformOn(result); // use return values, can also return promise
}); // error case gets handled for you

Which would let you do:

functionReturningAjax().then(function(transformedValue){
    // access to transformed value here
},function(err){
   // then accepts an optional second argument for errors, use it to handle errors.
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top