4

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());
    }
2
  • if there are async function.. then those functions has to return a promise or need to support a callback mechanism... only then you can do it Commented Jul 24, 2014 at 10:23
  • the async functions will return promises, the others won't though Commented Jul 24, 2014 at 10:25

1 Answer 1

29

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");
Sign up to request clarification or add additional context in comments.

3 Comments

Now that is beautiful. :-)
@Roamer-1888: That seems to be true in the current implementation; I don't see it documented, though, do you? But with the way functions get passed around in promise-based code, it does seem like they're unlikely to change it (the implementation)...
I certainly learned about .resolve's and .reject's "detachability", as they called it, from formal jQuery documentation. I can no longer find the original text but recall that it was an earlier version of the jQuery.Deferred() page. However, this feature is at least acknowledged, if not actually documented, in the Deferred examples at learn.jQuery.com . Look for phrases such as .then( defer.resolve, defer.reject ), setTimeout( defer.resolve, ...) and image.onerror = defer.reject.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.