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
  • 60,309
  • 67
  • 216
  • 347
Alex
  • 66,732
  • 177
  • 439
  • 641

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
  • 630,263
  • 148
  • 957
  • 1,375
0
rend().then(function() { d.resolve(); }

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

Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
  • 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