katie
katie

Reputation: 1041

reject deferred inside jQuery ajax

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?

Upvotes: 4

Views: 3215

Answers (2)

Bergi
Bergi

Reputation: 664548

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) {
  // …
});

Upvotes: 5

Sergey
Sergey

Reputation: 5476

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...
});

Upvotes: 0

Related Questions