AsyncIteratorClose.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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/12.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 $then(
  26. $then(
  27. $then(
  28. new $Promise(function (resolve) {
  29. resolve(GetMethod(iterator, 'return')); // step 4
  30. // resolve(Call(ret, iterator, [])); // step 6
  31. }),
  32. function (returnV) { // step 5.a
  33. if (typeof returnV === 'undefined') {
  34. return completion; // step 5.b
  35. }
  36. return Call(returnV, iterator); // step 5.c, 5.d.
  37. }
  38. ),
  39. null,
  40. function (e) {
  41. if (completion.type() === 'throw') {
  42. completion['?'](); // step 6
  43. } else {
  44. throw e; // step 7
  45. }
  46. }
  47. ),
  48. function (innerResult) { // step 8
  49. if (completion.type() === 'throw') {
  50. completion['?'](); // step 6
  51. }
  52. if (Type(innerResult) !== 'Object') {
  53. throw new $TypeError('`innerResult` must be an Object'); // step 10
  54. }
  55. return completion;
  56. }
  57. );
  58. };