javascriptnode.jspromisees6-promise

Is Node.js native Promise.all processing in parallel or sequentially?


I would like to clarify this point, as the documentation is not too clear about it;

Q1: Is Promise.all(iterable) processing all promises sequentially or in parallel? Or, more specifically, is it the equivalent of running chained promises like

p1.then(p2).then(p3).then(p4).then(p5)....

or is it some other kind of algorithm where all p1, p2, p3, p4, p5, etc. are being called at the same time (in parallel) and results are returned as soon as all resolve (or one rejects)?

Q2: If Promise.all runs in parallel, is there a convenient way to run an iterable sequencially?

Note: I don't want to use Q, or Bluebird, but all native ES6 specs.


Solution

  • Is Promise.all(iterable) executing all promises?

    No, promises cannot "be executed", they do not consist of code that can be run. A promise is created when you start a task, and it represents the results only. It is your code that is executing everything in parallel, by starting all tasks at once to run concurrently. This happens even before (and would also happen without) passing the promises to Promise.all.

    Promise.all does only await multiple promises. It doesn't care in what order they get resolved by those tasks, or whether the computations are running in parallel.

    is there a convenient way to run an iterable sequencially?

    If you already have your promises, you can't do much but Promise.all([p1, p2, p3, …]) (which does not have a notion of sequence). But if you do have an iterable of asynchronous functions, you can indeed run them sequentially. Basically you need to get from

    [fn1, fn2, fn3, …]
    

    to

    fn1().then(fn2).then(fn3).then(…)
    

    and the solution to do that is using Array::reduce:

    iterable.reduce((p, fn) => p.then(fn), Promise.resolve())