esnext.async-iterator.flat-map.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict';
  2. // https://github.com/tc39/proposal-iterator-helpers
  3. var $ = require('../internals/export');
  4. var call = require('../internals/function-call');
  5. var aCallable = require('../internals/a-callable');
  6. var anObject = require('../internals/an-object');
  7. var createAsyncIteratorProxy = require('../internals/async-iterator-create-proxy');
  8. var getAsyncIterator = require('../internals/get-async-iterator');
  9. var AsyncIteratorProxy = createAsyncIteratorProxy(function (Promise) {
  10. var state = this;
  11. var mapper = state.mapper;
  12. var innerIterator;
  13. return new Promise(function (resolve, reject) {
  14. var outerLoop = function () {
  15. try {
  16. Promise.resolve(anObject(call(state.next, state.iterator))).then(function (step) {
  17. try {
  18. if (anObject(step).done) {
  19. state.done = true;
  20. resolve({ done: true, value: undefined });
  21. } else {
  22. Promise.resolve(mapper(step.value)).then(function (mapped) {
  23. try {
  24. state.innerIterator = innerIterator = getAsyncIterator(mapped);
  25. state.innerNext = aCallable(innerIterator.next);
  26. return innerLoop();
  27. } catch (error2) { reject(error2); }
  28. }, reject);
  29. }
  30. } catch (error1) { reject(error1); }
  31. }, reject);
  32. } catch (error) { reject(error); }
  33. };
  34. var innerLoop = function () {
  35. if (innerIterator = state.innerIterator) {
  36. try {
  37. Promise.resolve(anObject(call(state.innerNext, innerIterator))).then(function (result) {
  38. try {
  39. if (anObject(result).done) {
  40. state.innerIterator = state.innerNext = null;
  41. outerLoop();
  42. } else resolve({ done: false, value: result.value });
  43. } catch (error1) { reject(error1); }
  44. }, reject);
  45. } catch (error) { reject(error); }
  46. } else outerLoop();
  47. };
  48. innerLoop();
  49. });
  50. });
  51. $({ target: 'AsyncIterator', proto: true, real: true, forced: true }, {
  52. flatMap: function flatMap(mapper) {
  53. return new AsyncIteratorProxy({
  54. iterator: anObject(this),
  55. mapper: aCallable(mapper),
  56. innerIterator: null,
  57. innerNext: null
  58. });
  59. }
  60. });