0

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?

k0pernikus
  • 50,568
  • 57
  • 198
  • 317
Alex
  • 64,868
  • 164
  • 416
  • 621

2 Answers2

4

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)
},
Community
  • 1
  • 1
Bergi
  • 572,313
  • 128
  • 898
  • 1,281
0
rend().then(function() { d.resolve(); }

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

Adam
  • 46,658
  • 11
  • 63
  • 84
  • 1
    Yes. You'd also need to use the failure for a rejection. [Or just don't do this](http://stackoverflow.com/q/23803743/1048572) – Bergi Feb 03 '15 at 23:53