Thursday 22 August 2013

Chaining jQuery promises/deferreds

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

No comments:

Post a Comment