promise.js 570 B

12345678910111213141516
  1. /**
  2. * run `fn` in serie for all values, and resolve with an array of the results
  3. * inspired by https://stackoverflow.com/a/50506360/1314820
  4. * @template T the input array's item type
  5. * @template V the `fn` function's return type
  6. * @param {T[]} values
  7. * @param {(item: T) => Promise<V>} fn
  8. * @returns {V[]}
  9. */
  10. export function mapSeries(values, fn) {
  11. return values.reduce(async (promiseChain, value) => {
  12. const chainResults = await promiseChain
  13. const currentResult = await fn(value)
  14. return [...chainResults, currentResult]
  15. }, Promise.resolve([]))
  16. }