doberkofler doberkofler - 5 months ago 41
Javascript Question

Serial execution of functions returning promises

With ES2016 we now have promises and that's great. Unfortunately the functionality is very minimalistic and there is nothing like the series or waterfall as available in the async package.
If there a package providing this functionality for promises or how do people typically deal with those use cases?

Answer Source

To serially execute an array of functions returning promises you can use Array.prototype.reduce:

let final = functions.reduce((prev, f) => prev.then(f), Promise.resolve());

The "initial" argument Promise.resolve() is there to seed the chain of promises, since otherwise (if passed an array containing only a single function) the .reduce callback never gets called.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download