javascriptpromiseq

Serialize a list of js promises call


what's the most convenient way to serialize a bunch of promised function call?

var promised_functions = [
 fn1,  // call this 
 fn2,  // if previous resolved call this
 fn3   // if previous resolved call this
];
q.serialize_functions(promised_functions)
.then(function(){
 // if all promises resolved do some
})

Solution

  • You can find the solution in the documentation:

    promised_functions.reduce(Q.when, Q()).then(function () {
        // if all promises resolved do some
    });
    

    Skip down to the "Sequences" section of the documentation. To copy it verbatim:


    If you have a number of promise-producing functions that need to be run sequentially, you can of course do so manually:

    return foo(initialVal).then(bar).then(baz).then(qux);
    

    However, if you want to run a dynamically constructed sequence of functions, you'll want something like this:

    var funcs = [foo, bar, baz, qux];
    
    var result = Q(initialVal);
    funcs.forEach(function (f) {
        result = result.then(f);
    });
    return result;
    

    You can make this slightly more compact using reduce:

    return funcs.reduce(function (soFar, f) {
        return soFar.then(f);
    }, Q(initialVal));
    

    Or, you could use th ultra-compact version:

    return funcs.reduce(Q.when, Q());
    

    There you have it. Straight from the horse's mouth.