Serial execution of functions returning promises

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-08 05:37:56

问题


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.


来源:https://stackoverflow.com/questions/42204008/serial-execution-of-functions-returning-promises

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!