async-from-sync-iterator.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict';
  2. var call = require('../internals/function-call');
  3. var anObject = require('../internals/an-object');
  4. var create = require('../internals/object-create');
  5. var getMethod = require('../internals/get-method');
  6. var defineBuiltIns = require('../internals/define-built-ins');
  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 createIterResultObject = require('../internals/create-iter-result-object');
  11. var Promise = getBuiltIn('Promise');
  12. var ASYNC_FROM_SYNC_ITERATOR = 'AsyncFromSyncIterator';
  13. var setInternalState = InternalStateModule.set;
  14. var getInternalState = InternalStateModule.getterFor(ASYNC_FROM_SYNC_ITERATOR);
  15. var asyncFromSyncIteratorContinuation = function (result, resolve, reject) {
  16. var done = result.done;
  17. Promise.resolve(result.value).then(function (value) {
  18. resolve(createIterResultObject(value, done));
  19. }, reject);
  20. };
  21. var AsyncFromSyncIterator = function AsyncIterator(iteratorRecord) {
  22. iteratorRecord.type = ASYNC_FROM_SYNC_ITERATOR;
  23. setInternalState(this, iteratorRecord);
  24. };
  25. AsyncFromSyncIterator.prototype = defineBuiltIns(create(AsyncIteratorPrototype), {
  26. next: function next() {
  27. var state = getInternalState(this);
  28. return new Promise(function (resolve, reject) {
  29. var result = anObject(call(state.next, state.iterator));
  30. asyncFromSyncIteratorContinuation(result, resolve, reject);
  31. });
  32. },
  33. 'return': function () {
  34. var iterator = getInternalState(this).iterator;
  35. return new Promise(function (resolve, reject) {
  36. var $return = getMethod(iterator, 'return');
  37. if ($return === undefined) return resolve(createIterResultObject(undefined, true));
  38. var result = anObject(call($return, iterator));
  39. asyncFromSyncIteratorContinuation(result, resolve, reject);
  40. });
  41. }
  42. });
  43. module.exports = AsyncFromSyncIterator;