4

I'm using $.ajax to get some HTML from the server.

my javascript makes use of promises and I want to avoid creating another promise and use jQuery ajax since it's already a promise.

But is there some way I can reject the promise inside the "done" callback?

my code looks something like this:

function get_html(){

   return $.ajax({ .... }).done(function(response){

     if(response.haveErrors){
       // here how do I reject and return the promise?
       return;
     }

     // code #2 should run normally
     // but can i pass a "parameter" to done() ?

   }).fail(function(){
      ....
   });
}

and the usage:

get_html().done(function(parameter){
      // code #2
    }).fail(function(){

});

Also, is it possible to pass a parameter to code # 2? in the done callback?

Liam
  • 27,717
  • 28
  • 128
  • 190
katie
  • 991
  • 2
  • 11
  • 19
  • 1
    possible duplicate of [jQuery Deferred: Rejecting a Promise from within a Done Filter](http://stackoverflow.com/questions/17800176/jquery-deferred-rejecting-a-promise-from-within-a-done-filter) – Artyom Neustroev Apr 02 '15 at 09:24

2 Answers2

5

Is there some way I can reject the promise inside the "done" callback?

No, because done does not create a new promise, and is only called when the promise is already fulfilled. You need to use then for chaining - it creates a new promise that can be rejected from the callback. However, with jQuery this is a bit more complicated, we cannot just throw in the callback.

So use

function get_html() {
    return $.ajax({…}).then(function(response) {
        if (response.hasErrors) {
            return $.Deferred().reject(response.errors);
        }
        // else
        return response; // which is getting passed as the parameter below
    });
}

and then

get_html().then(function(parameter) {
  // code #2
}, function(err) {
  // …
});
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

Seems like your code should be like below:

function get_html(){
    return $.ajax({ .... });
}

get_html().done(function(response){
    // process a response from your server here...
}).fail(function(){
    // process errors here...
});
Sergey
  • 5,396
  • 3
  • 26
  • 38
  • I dont want to process the response from my server there. That get_html function is supposed to be used in multiple places. I don't want to copy the code in every place :( – katie Apr 02 '15 at 10:16