2

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.

Mike McFarland
  • 657
  • 4
  • 17
  • [This any use](http://stackoverflow.com/questions/5627284/pass-in-an-array-of-deferreds-to-when)? – Andy Nov 05 '13 at 15:02
  • no not really. Though that's a useful technique (for more then just $.when) 'when' doesn't execute functions the same way as when you chain with 'then'. Semantically thats saying, wait for all of these to complete then execute. What I'm looking for is, when this completes do `A`, when the result from `A` completes, do `B`, when the result from `B` completes do `C`... – Mike McFarland Nov 05 '13 at 15:07

1 Answers1

4

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!')})
orange
  • 7,755
  • 14
  • 75
  • 139
  • thanks, besides the small typo that works fine. I suppose I can just make a utility method around for wrapping them up pretty easily. here's a fiddle of it working http://jsfiddle.net/mikedmcfarland/nEqkp/ I'd correct sequence.lenght however its a change smaller then 6 chars – Mike McFarland Nov 05 '13 at 15:15