Mike McFarland
Mike McFarland

Reputation: 657

Create a jquery promise from an array of promises to be executed sequentially

Does jquery have support for forming promises from an array of promises (or functions) to be executed in sequence? For example,

lets suppose I have this function defined

function wait(/*args*/){
    var complete = $.Deferred();
    var args = arguments;
    setTimeout(function(){
        console.log(args);
        //arguments are applied to show that the functionality should
        //pass arguments between promises in sequence.
        complete.resolve.apply(null,args);
    }, 1000);
    return complete.promise();
}

I could easily chain these together to form a new promise like so:

var sequencePromise = wait("first")
.then(wait.bind(null,"second"))
.then(wait.bind(null,"third"));

However i regularly have a long series of promises to sequence, or perhaps they are variable lists i am composing, so I am looking for a way to easily do something like:

var sequence = [
    wait("first"),
    wait.bind(null,"second"),
    wait.bind(null,"third")];

var sequencePromise = $.whenInSeq(sequence)

preferably, I'm looking for a solution that isn't a large dependency (it'd be ideal if I just missed something within the jquery api). Wanted to confirm something doesn't exist before I roll my own.

Upvotes: 2

Views: 337

Answers (1)

orange
orange

Reputation: 8068

try this (untested):

var sequence = [
    wait("first"),
    wait.bind(null,"second"),
    wait.bind(null,"third")];

var s = sequence[0];
for (var i = 1; i < sequence.length; i++) {
  s = s.then(sequence[i]);
}
s.done(function () {alert('done!')})

Upvotes: 4

Related Questions