Serial execution of functions returning promises

2019-05-31 14:37发布

问题:

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?

回答1:

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.



回答2:

Most of this functionality already exists (or will exist) in the language:

  • Run a bunch of actions simultaneously and get a Promise for an array of results: Promise.all()
  • Run a bunch of actions and get the Promise for the first that resolves/rejects: Promise.race()
  • Run a bunch of Promises serially: Use reduce() like the other answer mentions, or use the async iteration protocol.