esnext.async-iterator.drop.js 1.6 KB

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