esnext.async-iterator.take.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 anObject = require('../internals/an-object');
  6. var getIteratorDirect = require('../internals/get-iterator-direct');
  7. var notANaN = require('../internals/not-a-nan');
  8. var toPositiveInteger = require('../internals/to-positive-integer');
  9. var createAsyncIteratorProxy = require('../internals/async-iterator-create-proxy');
  10. var createIterResultObject = require('../internals/create-iter-result-object');
  11. var AsyncIteratorProxy = createAsyncIteratorProxy(function (Promise) {
  12. var state = this;
  13. var iterator = state.iterator;
  14. var returnMethod;
  15. if (!state.remaining--) {
  16. var resultDone = createIterResultObject(undefined, true);
  17. state.done = true;
  18. returnMethod = iterator['return'];
  19. if (returnMethod !== undefined) {
  20. return Promise.resolve(call(returnMethod, iterator, undefined)).then(function () {
  21. return resultDone;
  22. });
  23. }
  24. return resultDone;
  25. } return Promise.resolve(call(state.next, iterator)).then(function (step) {
  26. if (anObject(step).done) {
  27. state.done = true;
  28. return createIterResultObject(undefined, true);
  29. } return createIterResultObject(step.value, false);
  30. }).then(null, function (error) {
  31. state.done = true;
  32. throw error;
  33. });
  34. });
  35. $({ target: 'AsyncIterator', proto: true, real: true, forced: true }, {
  36. take: function take(limit) {
  37. return new AsyncIteratorProxy(getIteratorDirect(this), {
  38. remaining: toPositiveInteger(notANaN(+limit))
  39. });
  40. }
  41. });