0

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.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
user1492442
  • 239
  • 3
  • 13
  • From the [documentation](http://api.jquery.com/jQuery.ajax/#jqXHR) *"The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface"*. Hence I'd argue it does not implement the deferred API and cannot be resolved with a custom value. The value is essentially a promise. Using your own deferred object seems totally fine by me. – Felix Kling May 12 '14 at 04:23
  • Is there a reason to do this: def.resolved('whatever') vs. def.resolved('whatever').promise()? – user1492442 May 12 '14 at 05:25
  • What is the problem that you are trying to solve? Explain in terms of what your use case is. Avoid the [XY problem](http://meta.tex.stackexchange.com/questions/2449/what-does-xy-problem-mean) description. – Serendipity May 12 '14 at 06:52

1 Answers1

2

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.
});
Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • This looks good, but the reason I was using the deferred is because the method i need to call is in another module that I import.. SO, I need a hook. That hook was, I was hoping - the deferred.. like an "emitter".. basically, resolving it -- THUS enabling my function in another module to fire. Because in that module - I was using ".done( function(){ //do something})". So, if I didn't include the module.. no harm.. if i did, then it would be able to act upon the deferreds created in the parent module. – user1492442 May 14 '14 at 07:51
  • Benjamin - I accepted your answer, but I also asked another for a workaround for this anti-pattern: http://stackoverflow.com/questions/23657518/is-there-a-way-to-trigger-call-a-method-in-another-module-that-might-exist – user1492442 May 14 '14 at 14:33
  • I added an answer to that too, see if it helps you – Benjamin Gruenbaum May 14 '14 at 14:40