NewPromiseCapability.js 1.2 KB

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