esnext.async-iterator.take.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var call = require('../internals/function-call');
  4. var anObject = require('../internals/an-object');
  5. var getIteratorDirect = require('../internals/get-iterator-direct');
  6. var notANaN = require('../internals/not-a-nan');
  7. var toPositiveInteger = require('../internals/to-positive-integer');
  8. var createAsyncIteratorProxy = require('../internals/async-iterator-create-proxy');
  9. var createIterResultObject = require('../internals/create-iter-result-object');
  10. var IS_PURE = require('../internals/is-pure');
  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. // `AsyncIterator.prototype.take` method
  36. // https://github.com/tc39/proposal-async-iterator-helpers
  37. $({ target: 'AsyncIterator', proto: true, real: true, forced: IS_PURE }, {
  38. take: function take(limit) {
  39. anObject(this);
  40. var remaining = toPositiveInteger(notANaN(+limit));
  41. return new AsyncIteratorProxy(getIteratorDirect(this), {
  42. remaining: remaining
  43. });
  44. }
  45. });