AsyncIteratorClose.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $SyntaxError = require('es-errors/syntax');
  4. var $TypeError = require('es-errors/type');
  5. var $Promise = GetIntrinsic('%Promise%', true);
  6. var Call = require('./Call');
  7. var CompletionRecord = require('./CompletionRecord');
  8. var GetMethod = require('./GetMethod');
  9. var Type = require('./Type');
  10. var isIteratorRecord = require('../helpers/records/iterator-record');
  11. var callBound = require('call-bind/callBound');
  12. var $then = callBound('Promise.prototype.then', true);
  13. // https://262.ecma-international.org/9.0/#sec-asynciteratorclose
  14. module.exports = function AsyncIteratorClose(iteratorRecord, completion) {
  15. if (!isIteratorRecord(iteratorRecord)) {
  16. throw new $TypeError('Assertion failed: `iteratorRecord` must be an Iterator Record'); // step 1
  17. }
  18. if (!(completion instanceof CompletionRecord)) {
  19. throw new $TypeError('Assertion failed: completion is not a Completion Record instance'); // step 2
  20. }
  21. if (!$then) {
  22. throw new $SyntaxError('This environment does not support Promises.');
  23. }
  24. var iterator = iteratorRecord['[[Iterator]]']; // step 3
  25. return new $Promise(function (resolve) {
  26. var ret = GetMethod(iterator, 'return'); // step 4
  27. if (typeof ret === 'undefined') {
  28. resolve(completion); // step 5
  29. } else {
  30. resolve($then(
  31. new $Promise(function (resolve2) {
  32. // process.exit(42);
  33. resolve2(Call(ret, iterator, [])); // step 6
  34. }),
  35. function (innerResult) {
  36. if (Type(innerResult) !== 'Object') {
  37. throw new $TypeError('`innerResult` must be an Object'); // step 10
  38. }
  39. return completion;
  40. },
  41. function (e) {
  42. if (completion.type() === 'throw') {
  43. completion['?'](); // step 8
  44. } else {
  45. throw e; // step 9
  46. }
  47. }
  48. ));
  49. }
  50. });
  51. };