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.
var queue = [syncFunction, syncFunc2, returnsPromiseAsync];
var d = $.Deferred().resolve();
while (queue.length > 0) {
d = d.then(queue.shift()); // you don't need the `.done`
}
(fiddle)
Alternatively, you can reduce;
var res = queue.reduce(function(prev,cur){ // chain to res later to hook on done
return prev.then(cur);
}, $.Deferred().resolve());
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 initial Deferred
in a setTimeout
:
var p = $.Deferred();
var res = queue.reduce(function(prev,cur){ // chain to res later to hook on done
return prev.then(cur);
}, p);
setTimeout(p.resolve.bind(p), 0);
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 on res
:
res.then(function() {
// All functions have now completed
});
For those situations, here's a simple wrapper function that does both:
function clearQueue(q) {
var p = $.Deferred();
setTimeout(p.resolve.bind(p), 0);
return q.reduce(function(prev,cur){
return prev.then(cur);
}, p);
}
Example use (fiddle):
clearQueue(queue).then(function() {
console.log("All done");
});
console.log("This runs before any queued function starts");