Alex
Alex

Reputation: 68036

How to return promise in ajax done callback?

I'm trying to use promises to delay a function:

load: function(){

   var d = $.Deferred();

   $.ajax(......).done(function(resp){
      if(resp.error)
        return d.reject();

      ....
      return rend(); 
   });

   return d.promise();

},

I know $.ajax already returns a promise, but here render() will also return a promise so I cannot just use the $.ajax promise because

load.then(function() {   .....  })

should run after rend() completes.

Do you know how could I "merge" the rend() promise with d?

Upvotes: 0

Views: 2162

Answers (2)

Bergi
Bergi

Reputation: 664599

here render() will also return a promise so I cannot just use the $.ajax promise because load.then(function() { ..... }) should run after rend() completes.

Yes you can! That's just the power of then over done: it chains the actions, waiting for the result of the callback (render()) before resolving the returned promise.

Use

load: function(){
  return $.ajax(…).then(function(resp){
//                 ^^^^
    if(resp.error)
      return $.Deferred().reject(resp.error);

      …
      return render(); 
   }); // this will resolve with the result of your render() promise
       // (or be rejeced with the .error)
},

Upvotes: 4

Adam Jenkins
Adam Jenkins

Reputation: 55643

rend().then(function() { d.resolve(); }

Call rend and then use the success/failure of that promise to resolve/reject d.

Upvotes: 0

Related Questions