I am fairly new to using Promises and have a hard time of wrapping my head around jQuery deferreds.
What I currently have is an array of functions which I execute at a certain point:
while (queue.length) {
(queue.shift())();
}
The problem with this is, that some of those functions are asynchronous, but I need them to run one after another.
So some of the functions in the queue return a deferred (e.g. via jQuery.ajax()) and some are just normal functions. I would like to know if how it would be possible to execute them in order + sequentially (executing the next function only when the previous one has finished).
I thought maybe jQuery.when would be what I am looking for, but I can't figure out how to it exactly, I came only up with this:
var deferred = jQuery.Deferred();
while (queue.length > 0) {
deferred.done().then(queue.shift());
}
Very astute,
jQuery.when
is what you're looking for. It takes either a promise or a normal non-thenable and returns a promise over that value. However, since you have functions and not values here that isn't really required since this is the behavior of.then
anyway.(fiddle)
Alternatively, you can reduce;
If you have more code doing things below this, since the functions in the queue may run synchronously or asynchronously (or some synchronous and then we hit an async one), to avoid chaos you may want to ensure that the functions always run asynchronously. You can easily do that by wrapping the
resolve
on the initialDeferred
in asetTimeout
:Now the process won't start until the timeout occurs, and any code following this will definitely run before the first function from the queue does. In my view, that's inconsistent with the semantics of jQuery's promises (because they are inconsistent about sync vs. async callbacks), but you may want the consistency.
If you need to know when the process completes, just use a
.then
handler onres
:For those situations, here's a simple wrapper function that does both:
Example use (fiddle):