esnext.async-iterator.reduce.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var call = require('../internals/function-call');
  4. var aCallable = require('../internals/a-callable');
  5. var anObject = require('../internals/an-object');
  6. var isObject = require('../internals/is-object');
  7. var getBuiltIn = require('../internals/get-built-in');
  8. var getIteratorDirect = require('../internals/get-iterator-direct');
  9. var closeAsyncIteration = require('../internals/async-iterator-close');
  10. var Promise = getBuiltIn('Promise');
  11. var $TypeError = TypeError;
  12. // `AsyncIterator.prototype.reduce` method
  13. // https://github.com/tc39/proposal-async-iterator-helpers
  14. $({ target: 'AsyncIterator', proto: true, real: true }, {
  15. reduce: function reduce(reducer /* , initialValue */) {
  16. var record = getIteratorDirect(this);
  17. var iterator = record.iterator;
  18. var next = record.next;
  19. var noInitial = arguments.length < 2;
  20. var accumulator = noInitial ? undefined : arguments[1];
  21. var counter = 0;
  22. aCallable(reducer);
  23. return new Promise(function (resolve, reject) {
  24. var ifAbruptCloseAsyncIterator = function (error) {
  25. closeAsyncIteration(iterator, reject, error, reject);
  26. };
  27. var loop = function () {
  28. try {
  29. Promise.resolve(anObject(call(next, iterator))).then(function (step) {
  30. try {
  31. if (anObject(step).done) {
  32. noInitial ? reject($TypeError('Reduce of empty iterator with no initial value')) : resolve(accumulator);
  33. } else {
  34. var value = step.value;
  35. if (noInitial) {
  36. noInitial = false;
  37. accumulator = value;
  38. loop();
  39. } else try {
  40. var result = reducer(accumulator, value, counter);
  41. var handler = function ($result) {
  42. accumulator = $result;
  43. loop();
  44. };
  45. if (isObject(result)) Promise.resolve(result).then(handler, ifAbruptCloseAsyncIterator);
  46. else handler(result);
  47. } catch (error3) { ifAbruptCloseAsyncIterator(error3); }
  48. }
  49. counter++;
  50. } catch (error2) { reject(error2); }
  51. }, reject);
  52. } catch (error) { reject(error); }
  53. };
  54. loop();
  55. });
  56. }
  57. });