async-iterator-map.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. var call = require('../internals/function-call');
  3. var aCallable = require('../internals/a-callable');
  4. var anObject = require('../internals/an-object');
  5. var isObject = require('../internals/is-object');
  6. var getIteratorDirect = require('../internals/get-iterator-direct');
  7. var createAsyncIteratorProxy = require('../internals/async-iterator-create-proxy');
  8. var createIterResultObject = require('../internals/create-iter-result-object');
  9. var closeAsyncIteration = require('../internals/async-iterator-close');
  10. var AsyncIteratorProxy = createAsyncIteratorProxy(function (Promise) {
  11. var state = this;
  12. var iterator = state.iterator;
  13. var mapper = state.mapper;
  14. return new Promise(function (resolve, reject) {
  15. var doneAndReject = function (error) {
  16. state.done = true;
  17. reject(error);
  18. };
  19. var ifAbruptCloseAsyncIterator = function (error) {
  20. closeAsyncIteration(iterator, doneAndReject, error, doneAndReject);
  21. };
  22. Promise.resolve(anObject(call(state.next, iterator))).then(function (step) {
  23. try {
  24. if (anObject(step).done) {
  25. state.done = true;
  26. resolve(createIterResultObject(undefined, true));
  27. } else {
  28. var value = step.value;
  29. try {
  30. var result = mapper(value, state.counter++);
  31. var handler = function (mapped) {
  32. resolve(createIterResultObject(mapped, false));
  33. };
  34. if (isObject(result)) Promise.resolve(result).then(handler, ifAbruptCloseAsyncIterator);
  35. else handler(result);
  36. } catch (error2) { ifAbruptCloseAsyncIterator(error2); }
  37. }
  38. } catch (error) { doneAndReject(error); }
  39. }, doneAndReject);
  40. });
  41. });
  42. // `AsyncIterator.prototype.map` method
  43. // https://github.com/tc39/proposal-iterator-helpers
  44. module.exports = function map(mapper) {
  45. anObject(this);
  46. aCallable(mapper);
  47. return new AsyncIteratorProxy(getIteratorDirect(this), {
  48. mapper: mapper
  49. });
  50. };