promiseReduce.js.flow 757 B

12345678910111213141516171819202122232425
  1. // @flow strict
  2. import isPromise from './isPromise';
  3. import { type PromiseOrValue } from './PromiseOrValue';
  4. /**
  5. * Similar to Array.prototype.reduce(), however the reducing callback may return
  6. * a Promise, in which case reduction will continue after each promise resolves.
  7. *
  8. * If the callback does not return a Promise, then this function will also not
  9. * return a Promise.
  10. */
  11. export default function promiseReduce<T, U>(
  12. values: $ReadOnlyArray<T>,
  13. callback: (U, T) => PromiseOrValue<U>,
  14. initialValue: PromiseOrValue<U>,
  15. ): PromiseOrValue<U> {
  16. return values.reduce(
  17. (previous, value) =>
  18. isPromise(previous)
  19. ? previous.then(resolved => callback(resolved, value))
  20. : callback(previous, value),
  21. initialValue,
  22. );
  23. }