esnext.async-iterator.map.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 isObject = require('../internals/is-object');
  8. var getIteratorDirect = require('../internals/get-iterator-direct');
  9. var createAsyncIteratorProxy = require('../internals/async-iterator-create-proxy');
  10. var createIterResultObject = require('../internals/create-iter-result-object');
  11. var closeAsyncIteration = require('../internals/async-iterator-close');
  12. var AsyncIteratorProxy = createAsyncIteratorProxy(function (Promise) {
  13. var state = this;
  14. var iterator = state.iterator;
  15. var mapper = state.mapper;
  16. return new Promise(function (resolve, reject) {
  17. var doneAndReject = function (error) {
  18. state.done = true;
  19. reject(error);
  20. };
  21. var ifAbruptCloseAsyncIterator = function (error) {
  22. closeAsyncIteration(iterator, doneAndReject, error, doneAndReject);
  23. };
  24. Promise.resolve(anObject(call(state.next, iterator))).then(function (step) {
  25. try {
  26. if (anObject(step).done) {
  27. state.done = true;
  28. resolve(createIterResultObject(undefined, true));
  29. } else {
  30. var value = step.value;
  31. try {
  32. var result = mapper(value, state.counter++);
  33. var handler = function (mapped) {
  34. resolve(createIterResultObject(mapped, false));
  35. };
  36. if (isObject(result)) Promise.resolve(result).then(handler, ifAbruptCloseAsyncIterator);
  37. else handler(result);
  38. } catch (error2) { ifAbruptCloseAsyncIterator(error2); }
  39. }
  40. } catch (error) { doneAndReject(error); }
  41. }, doneAndReject);
  42. });
  43. });
  44. $({ target: 'AsyncIterator', proto: true, real: true, forced: true }, {
  45. map: function map(mapper) {
  46. return new AsyncIteratorProxy(getIteratorDirect(this), {
  47. mapper: aCallable(mapper)
  48. });
  49. }
  50. });