Appetere
Appetere

Reputation: 6261

Chaining jQuery promises/deferreds

I have a process where I have to send an ajax request to the server, but need to stop a scheduler before the ajax request begins, then restart the scheduler when the request is done.

I have got this working using the following code:

scheduler.stop()
         .done(function () {
                 setQuestionStatus().done(scheduler.start);
               });

But it seems that there should be a simpler way to write this, such as:

scheduler.stop().then(setQuestionStatus).then(scheduler.start); 

My problem is that when written this way, setQuestionStatus and scheduler.start are both called as soon as scheduler.stop has resolved, rather than after each item in the chain has resolved.

Can anyone tell me what I'm doing wrong in the second example?


For your information, both scheduler.stop and setQuestionStatus return a promise using the pattern:

var setQuestionStatus = function(){
  return $.Deferred(function (def) {
    // Do stuff
    def.resolve();
  }).promise();
}

Upvotes: 0

Views: 617

Answers (1)

Bergi
Bergi

Reputation: 664297

scheduler.stop().then(setQuestionStatus).then(scheduler.start); 

My problem is that when written this way, setQuestionStatus and scheduler.start are both called as soon as scheduler.stop has resolved, rather than after each item in the chain has resolved.

That's ugly non-standard behavior found in earlier versions of jQuery. Either update your copy to 1.8+ for using then, or use the pipe method instead.

Upvotes: 1

Related Questions