promiseReduce.mjs 630 B

1234567891011121314151617181920
  1. import { isPromise } from './isPromise.mjs';
  2. /**
  3. * Similar to Array.prototype.reduce(), however the reducing callback may return
  4. * a Promise, in which case reduction will continue after each promise resolves.
  5. *
  6. * If the callback does not return a Promise, then this function will also not
  7. * return a Promise.
  8. */
  9. export function promiseReduce(values, callbackFn, initialValue) {
  10. let accumulator = initialValue;
  11. for (const value of values) {
  12. accumulator = isPromise(accumulator)
  13. ? accumulator.then((resolved) => callbackFn(resolved, value))
  14. : callbackFn(accumulator, value);
  15. }
  16. return accumulator;
  17. }