async-from-sync-iterator.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. var apply = require('../internals/function-apply');
  3. var anObject = require('../internals/an-object');
  4. var create = require('../internals/object-create');
  5. var getMethod = require('../internals/get-method');
  6. var redefineAll = require('../internals/redefine-all');
  7. var InternalStateModule = require('../internals/internal-state');
  8. var getBuiltIn = require('../internals/get-built-in');
  9. var AsyncIteratorPrototype = require('../internals/async-iterator-prototype');
  10. var Promise = getBuiltIn('Promise');
  11. var ASYNC_FROM_SYNC_ITERATOR = 'AsyncFromSyncIterator';
  12. var setInternalState = InternalStateModule.set;
  13. var getInternalState = InternalStateModule.getterFor(ASYNC_FROM_SYNC_ITERATOR);
  14. var asyncFromSyncIteratorContinuation = function (result, resolve, reject) {
  15. var done = result.done;
  16. Promise.resolve(result.value).then(function (value) {
  17. resolve({ done: done, value: value });
  18. }, reject);
  19. };
  20. var AsyncFromSyncIterator = function AsyncIterator(iterator) {
  21. setInternalState(this, {
  22. type: ASYNC_FROM_SYNC_ITERATOR,
  23. iterator: anObject(iterator),
  24. next: iterator.next
  25. });
  26. };
  27. AsyncFromSyncIterator.prototype = redefineAll(create(AsyncIteratorPrototype), {
  28. next: function next(arg) {
  29. var state = getInternalState(this);
  30. var hasArg = !!arguments.length;
  31. return new Promise(function (resolve, reject) {
  32. var result = anObject(apply(state.next, state.iterator, hasArg ? [arg] : []));
  33. asyncFromSyncIteratorContinuation(result, resolve, reject);
  34. });
  35. },
  36. 'return': function (arg) {
  37. var iterator = getInternalState(this).iterator;
  38. var hasArg = !!arguments.length;
  39. return new Promise(function (resolve, reject) {
  40. var $return = getMethod(iterator, 'return');
  41. if ($return === undefined) return resolve({ done: true, value: arg });
  42. var result = anObject(apply($return, iterator, hasArg ? [arg] : []));
  43. asyncFromSyncIteratorContinuation(result, resolve, reject);
  44. });
  45. },
  46. 'throw': function (arg) {
  47. var iterator = getInternalState(this).iterator;
  48. var hasArg = !!arguments.length;
  49. return new Promise(function (resolve, reject) {
  50. var $throw = getMethod(iterator, 'throw');
  51. if ($throw === undefined) return reject(arg);
  52. var result = anObject(apply($throw, iterator, hasArg ? [arg] : []));
  53. asyncFromSyncIteratorContinuation(result, resolve, reject);
  54. });
  55. }
  56. });
  57. module.exports = AsyncFromSyncIterator;