How To Use Jquery Deferred (when/then, Etc.) To Fix Asynchroneous Pyramid Of Doom Issue
I've been puzzling for quite a while trying to wrap my head around JavaScript promises. I want to fix some issues with asynchroneous calls in my code, to de-spagethise it. But I'd
Solution 1:
But I can't get it to work
Some points:
- don't use an array of
deferreds
, even less a global one! Break it into single steps, and use a single promise for each step. - use the counter value to resolve the promise. A promise should always represent an (async) result.
- don't use
$.when
unless you need to wait for multiple promises then
does take a callback function. You must not calltakeStep()
, but pass it.
You also might want to have a look at this answer for rules-of-thumb to get familiar with promises.
// the most generic function that only waits and returns a promisefunctionwait(t, v) {
var d = new $.Deferred();
setTimeout(function() {
d.resolve(v);
}, t);
return d.promise();
}
// logs the value and returns the next numberfunctionmarkStep(nr) {
log('step ' + cntr + ': ' + getCurrentTime() );
return nr+1;
}
// waits before logging and returns a promise for the next numberfunctiontakeStep(nr) {
returnwait(stepTime, nr).then(markStep);
}
takeStep(0)
.then(takeStep)
.then(takeStep)
.then(takeStep)
.then(takeStep)
.done(function(nr) {
log('done (' + getCurrentTime() + ')');
});
Post a Comment for "How To Use Jquery Deferred (when/then, Etc.) To Fix Asynchroneous Pyramid Of Doom Issue"