NewPromiseCapability.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $TypeError = GetIntrinsic('%TypeError%');
  4. var IsCallable = require('es-abstract/2022/IsCallable');
  5. var IsConstructor = require('es-abstract/2022/IsConstructor');
  6. // https://262.ecma-international.org/6.0/#sec-newpromisecapability
  7. module.exports = function NewPromiseCapability(C) {
  8. if (!IsConstructor(C)) {
  9. throw new $TypeError('C must be a constructor'); // step 1
  10. }
  11. var resolvingFunctions = { '[[Resolve]]': void undefined, '[[Reject]]': void undefined }; // step 3
  12. var promise = new C(function (resolve, reject) { // steps 4-5
  13. if (typeof resolvingFunctions['[[Resolve]]'] !== 'undefined' || typeof resolvingFunctions['[[Reject]]'] !== 'undefined') {
  14. throw new $TypeError('executor has already been called'); // step 4.a, 4.b
  15. }
  16. resolvingFunctions['[[Resolve]]'] = resolve; // step 4.c
  17. resolvingFunctions['[[Reject]]'] = reject; // step 4.d
  18. }); // step 4-6
  19. if (!IsCallable(resolvingFunctions['[[Resolve]]']) || !IsCallable(resolvingFunctions['[[Reject]]'])) {
  20. throw new $TypeError('executor must provide valid resolve and reject functions'); // steps 7-8
  21. }
  22. return {
  23. '[[Promise]]': promise,
  24. '[[Resolve]]': resolvingFunctions['[[Resolve]]'],
  25. '[[Reject]]': resolvingFunctions['[[Reject]]']
  26. }; // step 9
  27. };