promiseReduce.js 759 B

123456789101112131415161718192021222324252627
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true,
  4. });
  5. exports.promiseReduce = promiseReduce;
  6. var _isPromise = require('./isPromise.js');
  7. /**
  8. * Similar to Array.prototype.reduce(), however the reducing callback may return
  9. * a Promise, in which case reduction will continue after each promise resolves.
  10. *
  11. * If the callback does not return a Promise, then this function will also not
  12. * return a Promise.
  13. */
  14. function promiseReduce(values, callbackFn, initialValue) {
  15. let accumulator = initialValue;
  16. for (const value of values) {
  17. accumulator = (0, _isPromise.isPromise)(accumulator)
  18. ? accumulator.then((resolved) => callbackFn(resolved, value))
  19. : callbackFn(accumulator, value);
  20. }
  21. return accumulator;
  22. }