promiseReduce.mjs 602 B

12345678910111213141516
  1. import isPromise from './isPromise';
  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 default function promiseReduce(values, callback, initialValue) {
  10. return values.reduce(function (previous, value) {
  11. return isPromise(previous) ? previous.then(function (resolved) {
  12. return callback(resolved, value);
  13. }) : callback(previous, value);
  14. }, initialValue);
  15. }