async-iterator-iteration.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict';
  2. // https://github.com/tc39/proposal-iterator-helpers
  3. var aFunction = require('../internals/a-function');
  4. var anObject = require('../internals/an-object');
  5. var getBuiltIn = require('../internals/get-built-in');
  6. var Promise = getBuiltIn('Promise');
  7. var push = [].push;
  8. var createMethod = function (TYPE) {
  9. var IS_TO_ARRAY = TYPE == 0;
  10. var IS_FOR_EACH = TYPE == 1;
  11. var IS_EVERY = TYPE == 2;
  12. var IS_SOME = TYPE == 3;
  13. return function (iterator, fn) {
  14. anObject(iterator);
  15. var next = aFunction(iterator.next);
  16. var array = IS_TO_ARRAY ? [] : undefined;
  17. if (!IS_TO_ARRAY) aFunction(fn);
  18. return new Promise(function (resolve, reject) {
  19. var loop = function () {
  20. try {
  21. Promise.resolve(anObject(next.call(iterator))).then(function (step) {
  22. try {
  23. if (anObject(step).done) {
  24. resolve(IS_TO_ARRAY ? array : IS_SOME ? false : IS_EVERY || undefined);
  25. } else {
  26. var value = step.value;
  27. if (IS_TO_ARRAY) {
  28. push.call(array, value);
  29. loop();
  30. } else {
  31. Promise.resolve(fn(value)).then(function (result) {
  32. if (IS_FOR_EACH) {
  33. loop();
  34. } else if (IS_EVERY) {
  35. result ? loop() : resolve(false);
  36. } else {
  37. result ? resolve(IS_SOME || value) : loop();
  38. }
  39. }, reject);
  40. }
  41. }
  42. } catch (err) { reject(err); }
  43. }, reject);
  44. } catch (error) { reject(error); }
  45. };
  46. loop();
  47. });
  48. };
  49. };
  50. module.exports = {
  51. toArray: createMethod(0),
  52. forEach: createMethod(1),
  53. every: createMethod(2),
  54. some: createMethod(3),
  55. find: createMethod(4)
  56. };