Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: execute array of functions sequentially (both deferreds and non-deferreds)

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());
    }
like image 652
Riesling Avatar asked Nov 28 '22 11:11

Riesling


1 Answers

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");
like image 116
Benjamin Gruenbaum Avatar answered Dec 04 '22 07:12

Benjamin Gruenbaum