esnext.async-iterator.drop.js 1.6 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 AsyncIteratorProxy = createAsyncIteratorProxy(function (Promise) {
  11. var state = this;
  12. return new Promise(function (resolve, reject) {
  13. var doneAndReject = function (error) {
  14. state.done = true;
  15. reject(error);
  16. };
  17. var loop = function () {
  18. try {
  19. Promise.resolve(anObject(call(state.next, state.iterator))).then(function (step) {
  20. try {
  21. if (anObject(step).done) {
  22. state.done = true;
  23. resolve(createIterResultObject(undefined, true));
  24. } else if (state.remaining) {
  25. state.remaining--;
  26. loop();
  27. } else resolve(createIterResultObject(step.value, false));
  28. } catch (err) { doneAndReject(err); }
  29. }, doneAndReject);
  30. } catch (error) { doneAndReject(error); }
  31. };
  32. loop();
  33. });
  34. });
  35. // `AsyncIterator.prototype.drop` method
  36. // https://github.com/tc39/proposal-async-iterator-helpers
  37. $({ target: 'AsyncIterator', proto: true, real: true }, {
  38. drop: function drop(limit) {
  39. return new AsyncIteratorProxy(getIteratorDirect(this), {
  40. remaining: toPositiveInteger(notANaN(+limit))
  41. });
  42. }
  43. });