async-iterator-create-proxy.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict';
  2. var path = require('../internals/path');
  3. var aFunction = require('../internals/a-function');
  4. var anObject = require('../internals/an-object');
  5. var create = require('../internals/object-create');
  6. var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
  7. var redefineAll = require('../internals/redefine-all');
  8. var wellKnownSymbol = require('../internals/well-known-symbol');
  9. var InternalStateModule = require('../internals/internal-state');
  10. var getBuiltIn = require('../internals/get-built-in');
  11. var Promise = getBuiltIn('Promise');
  12. var setInternalState = InternalStateModule.set;
  13. var getInternalState = InternalStateModule.get;
  14. var TO_STRING_TAG = wellKnownSymbol('toStringTag');
  15. var $return = function (value) {
  16. var iterator = getInternalState(this).iterator;
  17. var $$return = iterator['return'];
  18. return $$return === undefined
  19. ? Promise.resolve({ done: true, value: value })
  20. : anObject($$return.call(iterator, value));
  21. };
  22. var $throw = function (value) {
  23. var iterator = getInternalState(this).iterator;
  24. var $$throw = iterator['throw'];
  25. return $$throw === undefined
  26. ? Promise.reject(value)
  27. : $$throw.call(iterator, value);
  28. };
  29. module.exports = function (nextHandler, IS_ITERATOR) {
  30. var AsyncIteratorProxy = function AsyncIterator(state) {
  31. state.next = aFunction(state.iterator.next);
  32. state.done = false;
  33. setInternalState(this, state);
  34. };
  35. AsyncIteratorProxy.prototype = redefineAll(create(path.AsyncIterator.prototype), {
  36. next: function next(arg) {
  37. var state = getInternalState(this);
  38. if (state.done) return Promise.resolve({ done: true, value: undefined });
  39. try {
  40. return Promise.resolve(anObject(nextHandler.call(state, arg, Promise)));
  41. } catch (error) {
  42. return Promise.reject(error);
  43. }
  44. },
  45. 'return': $return,
  46. 'throw': $throw
  47. });
  48. if (!IS_ITERATOR) {
  49. createNonEnumerableProperty(AsyncIteratorProxy.prototype, TO_STRING_TAG, 'Generator');
  50. }
  51. return AsyncIteratorProxy;
  52. };