4

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
})
aleclofabbro
  • 1,635
  • 1
  • 18
  • 35
  • 2
    take a look to this question. I may found your answer : http://stackoverflow.com/questions/18386753/how-to-sequentially-run-promises-with-q-in-javascript – peernohell Sep 30 '13 at 16:18

2 Answers2

11

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.

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
  • 1
    oops! very true! sorry i've been doing a fast search using bad keywords (serie, serialize, chain ..) i didn't try "sequence" ! Thank you – aleclofabbro Sep 30 '13 at 17:20
0

Sometime for loop is not that bad.

for(const fn of asyncFns) {
  await fn()
}
Clem
  • 2,150
  • 15
  • 17