AsyncIteratorClose.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $SyntaxError = GetIntrinsic('%SyntaxError%');
  4. var $TypeError = GetIntrinsic('%TypeError%');
  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 assertRecord = require('../helpers/assertRecord');
  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. assertRecord(Type, 'Iterator Record', 'iteratorRecord', iteratorRecord); // step 1
  16. if (!(completion instanceof CompletionRecord)) {
  17. throw new $TypeError('Assertion failed: completion is not a Completion Record instance'); // step 2
  18. }
  19. if (!$then) {
  20. throw new $SyntaxError('This environment does not support Promises.');
  21. }
  22. var iterator = iteratorRecord['[[Iterator]]']; // step 3
  23. return new $Promise(function (resolve) {
  24. var ret = GetMethod(iterator, 'return'); // step 4
  25. if (typeof ret === 'undefined') {
  26. resolve(completion); // step 5
  27. } else {
  28. resolve($then(
  29. new $Promise(function (resolve2) {
  30. // process.exit(42);
  31. resolve2(Call(ret, iterator, [])); // step 6
  32. }),
  33. function (innerResult) {
  34. if (Type(innerResult) !== 'Object') {
  35. throw new $TypeError('`innerResult` must be an Object'); // step 10
  36. }
  37. return completion;
  38. },
  39. function (e) {
  40. if (completion.type() === 'throw') {
  41. completion['?'](); // step 8
  42. } else {
  43. throw e; // step 9
  44. }
  45. }
  46. ));
  47. }
  48. });
  49. };