PromiseConstructor.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. using Jint.Collections;
  2. using Jint.Native.Function;
  3. using Jint.Native.Iterator;
  4. using Jint.Native.Object;
  5. using Jint.Native.Symbol;
  6. using Jint.Runtime;
  7. using Jint.Runtime.Descriptors;
  8. using Jint.Runtime.Interop;
  9. namespace Jint.Native.Promise
  10. {
  11. internal sealed record PromiseCapability(
  12. JsValue PromiseInstance,
  13. ICallable Resolve,
  14. ICallable Reject,
  15. JsValue RejectObj,
  16. JsValue ResolveObj
  17. );
  18. internal sealed class PromiseConstructor : Constructor
  19. {
  20. private static readonly JsString _functionName = new JsString("Promise");
  21. internal PromiseConstructor(
  22. Engine engine,
  23. Realm realm,
  24. FunctionPrototype functionPrototype,
  25. ObjectPrototype objectPrototype)
  26. : base(engine, realm, _functionName)
  27. {
  28. _prototype = functionPrototype;
  29. PrototypeObject = new PromisePrototype(engine, realm, this, objectPrototype);
  30. _length = new PropertyDescriptor(1, PropertyFlag.Configurable);
  31. _prototypeDescriptor = new PropertyDescriptor(PrototypeObject, PropertyFlag.AllForbidden);
  32. }
  33. internal PromisePrototype PrototypeObject { get; }
  34. protected override void Initialize()
  35. {
  36. const PropertyFlag PropertyFlags = PropertyFlag.Configurable | PropertyFlag.Writable;
  37. const PropertyFlag LengthFlags = PropertyFlag.Configurable;
  38. var properties = new PropertyDictionary(6, checkExistingKeys: false)
  39. {
  40. ["all"] = new(new PropertyDescriptor(new ClrFunction(Engine, "all", All, 1, LengthFlags), PropertyFlags)),
  41. ["allSettled"] = new(new PropertyDescriptor(new ClrFunction(Engine, "allSettled", AllSettled, 1, LengthFlags), PropertyFlags)),
  42. ["any"] = new(new PropertyDescriptor(new ClrFunction(Engine, "any", Any, 1, LengthFlags), PropertyFlags)),
  43. ["race"] = new(new PropertyDescriptor(new ClrFunction(Engine, "race", Race, 1, LengthFlags), PropertyFlags)),
  44. ["reject"] = new(new PropertyDescriptor(new ClrFunction(Engine, "reject", Reject, 1, LengthFlags), PropertyFlags)),
  45. ["resolve"] = new(new PropertyDescriptor(new ClrFunction(Engine, "resolve", Resolve, 1, LengthFlags), PropertyFlags)),
  46. ["withResolvers"] = new(new PropertyDescriptor(new ClrFunction(Engine, "withResolvers", WithResolvers , 0, LengthFlags), PropertyFlags)),
  47. };
  48. SetProperties(properties);
  49. var symbols = new SymbolDictionary(1)
  50. {
  51. [GlobalSymbolRegistry.Species] = new GetSetPropertyDescriptor(
  52. get: new ClrFunction(_engine, "get [Symbol.species]", (thisObj, _) => thisObj, 0, PropertyFlag.Configurable),
  53. set: Undefined, PropertyFlag.Configurable)
  54. };
  55. SetSymbols(symbols);
  56. }
  57. /// <summary>
  58. /// https://tc39.es/ecma262/#sec-promise-executor
  59. /// </summary>
  60. public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget)
  61. {
  62. if (newTarget.IsUndefined())
  63. {
  64. ExceptionHelper.ThrowTypeError(_realm, "Constructor Promise requires 'new'");
  65. }
  66. if (arguments.At(0) is not ICallable executor)
  67. {
  68. ExceptionHelper.ThrowTypeError(_realm, $"Promise executor {(arguments.At(0))} is not a function");
  69. return null;
  70. }
  71. var promise = OrdinaryCreateFromConstructor(
  72. newTarget,
  73. static intrinsics => intrinsics.Promise.PrototypeObject,
  74. static (Engine engine, Realm _, object? _) => new JsPromise(engine));
  75. var (resolve, reject) = promise.CreateResolvingFunctions();
  76. try
  77. {
  78. executor.Call(Undefined, new JsValue[] { resolve, reject });
  79. }
  80. catch (JavaScriptException e)
  81. {
  82. reject.Call(JsValue.Undefined, new[] { e.Error });
  83. }
  84. return promise;
  85. }
  86. /// <summary>
  87. /// https://tc39.es/ecma262/#sec-promise.resolve
  88. /// </summary>
  89. internal JsValue Resolve(JsValue thisObject, JsValue[] arguments)
  90. {
  91. if (!thisObject.IsObject())
  92. {
  93. ExceptionHelper.ThrowTypeError(_realm, "PromiseResolve called on non-object");
  94. }
  95. if (thisObject is not IConstructor)
  96. {
  97. ExceptionHelper.ThrowTypeError(_realm, "Promise.resolve invoked on a non-constructor value");
  98. }
  99. var x = arguments.At(0);
  100. return PromiseResolve(thisObject, x);
  101. }
  102. private JsObject WithResolvers(JsValue thisObject, JsValue[] arguments)
  103. {
  104. var promiseCapability = NewPromiseCapability(_engine, thisObject);
  105. var obj = OrdinaryObjectCreate(_engine, _engine.Realm.Intrinsics.Object.PrototypeObject);
  106. obj.CreateDataPropertyOrThrow("promise", promiseCapability.PromiseInstance);
  107. obj.CreateDataPropertyOrThrow("resolve", promiseCapability.ResolveObj);
  108. obj.CreateDataPropertyOrThrow("reject", promiseCapability.RejectObj);
  109. return obj;
  110. }
  111. /// <summary>
  112. /// https://tc39.es/ecma262/#sec-promise-resolve
  113. /// </summary>
  114. private JsValue PromiseResolve(JsValue thisObject, JsValue x)
  115. {
  116. if (x.IsPromise())
  117. {
  118. var xConstructor = x.Get(CommonProperties.Constructor);
  119. if (SameValue(xConstructor, thisObject))
  120. {
  121. return x;
  122. }
  123. }
  124. var (instance, resolve, _, _, _) = NewPromiseCapability(_engine, thisObject);
  125. resolve.Call(Undefined, new[] { x });
  126. return instance;
  127. }
  128. /// <summary>
  129. /// https://tc39.es/ecma262/#sec-promise.reject
  130. /// </summary>
  131. private JsValue Reject(JsValue thisObject, JsValue[] arguments)
  132. {
  133. if (!thisObject.IsObject())
  134. {
  135. ExceptionHelper.ThrowTypeError(_realm, "Promise.reject called on non-object");
  136. }
  137. if (thisObject is not IConstructor)
  138. {
  139. ExceptionHelper.ThrowTypeError(_realm, "Promise.reject invoked on a non-constructor value");
  140. }
  141. var r = arguments.At(0);
  142. var (instance, _, reject, _, _) = NewPromiseCapability(_engine, thisObject);
  143. reject.Call(Undefined, new[] { r });
  144. return instance;
  145. }
  146. // This helper methods executes the first 6 steps in the specs belonging to static Promise methods like all, any etc.
  147. // If it returns false, that means it has an error and it is already rejected
  148. // If it returns true, the logic specific to the calling function should continue executing
  149. private bool TryGetPromiseCapabilityAndIterator(JsValue thisObject, JsValue[] arguments, string callerName, out PromiseCapability capability, out ICallable promiseResolve, out IteratorInstance iterator)
  150. {
  151. if (!thisObject.IsObject())
  152. {
  153. ExceptionHelper.ThrowTypeError(_realm, $"{callerName} called on non-object");
  154. }
  155. //2. Let promiseCapability be ? NewPromiseCapability(C).
  156. capability = NewPromiseCapability(_engine, thisObject);
  157. var reject = capability.Reject;
  158. //3. Let promiseResolve be GetPromiseResolve(C).
  159. // 4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  160. try
  161. {
  162. promiseResolve = GetPromiseResolve(thisObject);
  163. }
  164. catch (JavaScriptException e)
  165. {
  166. reject.Call(Undefined, new[] { e.Error });
  167. promiseResolve = null!;
  168. iterator = null!;
  169. return false;
  170. }
  171. // 5. Let iteratorRecord be GetIterator(iterable).
  172. // 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  173. try
  174. {
  175. if (arguments.Length == 0)
  176. {
  177. ExceptionHelper.ThrowTypeError(_realm, $"no arguments were passed to {callerName}");
  178. }
  179. var iterable = arguments.At(0);
  180. iterator = iterable.GetIterator(_realm);
  181. }
  182. catch (JavaScriptException e)
  183. {
  184. reject.Call(Undefined, new[] { e.Error });
  185. iterator = null!;
  186. return false;
  187. }
  188. return true;
  189. }
  190. // https://tc39.es/ecma262/#sec-promise.all
  191. private JsValue All(JsValue thisObject, JsValue[] arguments)
  192. {
  193. if (!TryGetPromiseCapabilityAndIterator(thisObject, arguments, "Promise.all", out var capability, out var promiseResolve, out var iterator))
  194. return capability.PromiseInstance;
  195. var (resultingPromise, resolve, reject, _, rejectObj) = capability;
  196. var results = new List<JsValue>();
  197. bool doneIterating = false;
  198. void ResolveIfFinished()
  199. {
  200. // that means all of them were resolved
  201. // Note that "Undefined" is not null, thus the logic is sound, even though awkward
  202. // also note that it is important to check if we are done iterating.
  203. // if "then" method is sync then it will be resolved BEFORE the next iteration cycle
  204. if (results.TrueForAll(static x => x is not null) && doneIterating)
  205. {
  206. var array = _realm.Intrinsics.Array.ConstructFast(results);
  207. resolve.Call(Undefined, new JsValue[] { array });
  208. }
  209. }
  210. // 27.2.4.1.2 PerformPromiseAll ( iteratorRecord, constructor, resultCapability, promiseResolve )
  211. // https://tc39.es/ecma262/#sec-performpromiseall
  212. try
  213. {
  214. int index = 0;
  215. do
  216. {
  217. JsValue value;
  218. try
  219. {
  220. if (!iterator.TryIteratorStep(out var nextItem))
  221. {
  222. doneIterating = true;
  223. ResolveIfFinished();
  224. break;
  225. }
  226. value = nextItem.Get(CommonProperties.Value);
  227. }
  228. catch (JavaScriptException e)
  229. {
  230. reject.Call(Undefined, new[] { e.Error });
  231. return resultingPromise;
  232. }
  233. // note that null here is important
  234. // it will help to detect if all inner promises were resolved
  235. // In F# it would be Option<JsValue>
  236. results.Add(null!);
  237. var item = promiseResolve.Call(thisObject, new JsValue[] { value });
  238. var thenProps = item.Get("then");
  239. if (thenProps is ICallable thenFunc)
  240. {
  241. var capturedIndex = index;
  242. var alreadyCalled = false;
  243. var onSuccess =
  244. new ClrFunction(_engine, "", (_, args) =>
  245. {
  246. if (!alreadyCalled)
  247. {
  248. alreadyCalled = true;
  249. results[capturedIndex] = args.At(0);
  250. ResolveIfFinished();
  251. }
  252. return Undefined;
  253. }, 1, PropertyFlag.Configurable);
  254. thenFunc.Call(item, new JsValue[] { onSuccess, rejectObj });
  255. }
  256. else
  257. {
  258. ExceptionHelper.ThrowTypeError(_realm, "Passed non Promise-like value");
  259. }
  260. index += 1;
  261. } while (true);
  262. }
  263. catch (JavaScriptException e)
  264. {
  265. iterator.Close(CompletionType.Throw);
  266. reject.Call(Undefined, new[] { e.Error });
  267. return resultingPromise;
  268. }
  269. return resultingPromise;
  270. }
  271. // https://tc39.es/ecma262/#sec-promise.allsettled
  272. private JsValue AllSettled(JsValue thisObject, JsValue[] arguments)
  273. {
  274. if (!TryGetPromiseCapabilityAndIterator(thisObject, arguments, "Promise.allSettled", out var capability, out var promiseResolve, out var iterator))
  275. return capability.PromiseInstance;
  276. var (resultingPromise, resolve, reject, _, rejectObj) = capability;
  277. var results = new List<JsValue>();
  278. bool doneIterating = false;
  279. void ResolveIfFinished()
  280. {
  281. // that means all of them were resolved
  282. // Note that "Undefined" is not null, thus the logic is sound, even though awkward
  283. // also note that it is important to check if we are done iterating.
  284. // if "then" method is sync then it will be resolved BEFORE the next iteration cycle
  285. if (results.TrueForAll(static x => x is not null) && doneIterating)
  286. {
  287. var array = _realm.Intrinsics.Array.ConstructFast(results);
  288. resolve.Call(Undefined, new JsValue[] { array });
  289. }
  290. }
  291. // 27.2.4.1.2 PerformPromiseAll ( iteratorRecord, constructor, resultCapability, promiseResolve )
  292. // https://tc39.es/ecma262/#sec-performpromiseall
  293. try
  294. {
  295. int index = 0;
  296. do
  297. {
  298. JsValue value;
  299. try
  300. {
  301. if (!iterator.TryIteratorStep(out var nextItem))
  302. {
  303. doneIterating = true;
  304. ResolveIfFinished();
  305. break;
  306. }
  307. value = nextItem.Get(CommonProperties.Value);
  308. }
  309. catch (JavaScriptException e)
  310. {
  311. reject.Call(Undefined, new[] { e.Error });
  312. return resultingPromise;
  313. }
  314. // note that null here is important
  315. // it will help to detect if all inner promises were resolved
  316. // In F# it would be Option<JsValue>
  317. results.Add(null!);
  318. var item = promiseResolve.Call(thisObject, new JsValue[] { value });
  319. var thenProps = item.Get("then");
  320. if (thenProps is ICallable thenFunc)
  321. {
  322. var capturedIndex = index;
  323. var alreadyCalled = false;
  324. var onSuccess =
  325. new ClrFunction(_engine, "", (_, args) =>
  326. {
  327. if (!alreadyCalled)
  328. {
  329. alreadyCalled = true;
  330. var res = Engine.Realm.Intrinsics.Object.Construct(2);
  331. res.FastSetDataProperty("status", "fulfilled");
  332. res.FastSetDataProperty("value", args.At(0));
  333. results[capturedIndex] = res;
  334. ResolveIfFinished();
  335. }
  336. return Undefined;
  337. }, 1, PropertyFlag.Configurable);
  338. var onFailure =
  339. new ClrFunction(_engine, "", (_, args) =>
  340. {
  341. if (!alreadyCalled)
  342. {
  343. alreadyCalled = true;
  344. var res = Engine.Realm.Intrinsics.Object.Construct(2);
  345. res.FastSetDataProperty("status", "rejected");
  346. res.FastSetDataProperty("reason", args.At(0));
  347. results[capturedIndex] = res;
  348. ResolveIfFinished();
  349. }
  350. return Undefined;
  351. }, 1, PropertyFlag.Configurable);
  352. thenFunc.Call(item, new JsValue[] { onSuccess, onFailure });
  353. }
  354. else
  355. {
  356. ExceptionHelper.ThrowTypeError(_realm, "Passed non Promise-like value");
  357. }
  358. index += 1;
  359. } while (true);
  360. }
  361. catch (JavaScriptException e)
  362. {
  363. iterator.Close(CompletionType.Throw);
  364. reject.Call(Undefined, new[] { e.Error });
  365. return resultingPromise;
  366. }
  367. return resultingPromise;
  368. }
  369. // https://tc39.es/ecma262/#sec-promise.any
  370. private JsValue Any(JsValue thisObject, JsValue[] arguments)
  371. {
  372. if (!TryGetPromiseCapabilityAndIterator(thisObject, arguments, "Promise.any", out var capability, out var promiseResolve, out var iterator))
  373. {
  374. return capability.PromiseInstance;
  375. }
  376. var (resultingPromise, resolve, reject, resolveObj, _) = capability;
  377. var errors = new List<JsValue>();
  378. var doneIterating = false;
  379. void RejectIfAllRejected()
  380. {
  381. // that means all of them were rejected
  382. // Note that "Undefined" is not null, thus the logic is sound, even though awkward
  383. // also note that it is important to check if we are done iterating.
  384. // if "then" method is sync then it will be resolved BEFORE the next iteration cycle
  385. if (errors.TrueForAll(static x => x is not null) && doneIterating)
  386. {
  387. var array = _realm.Intrinsics.Array.ConstructFast(errors);
  388. reject.Call(Undefined, new JsValue[] { Construct(_realm.Intrinsics.AggregateError, new JsValue[] { array }) });
  389. }
  390. }
  391. // https://tc39.es/ecma262/#sec-performpromiseany
  392. try
  393. {
  394. var index = 0;
  395. do
  396. {
  397. ObjectInstance? nextItem = null;
  398. JsValue value;
  399. try
  400. {
  401. if (!iterator.TryIteratorStep(out nextItem))
  402. {
  403. doneIterating = true;
  404. RejectIfAllRejected();
  405. break;
  406. }
  407. value = nextItem.Get(CommonProperties.Value);
  408. }
  409. catch (JavaScriptException e)
  410. {
  411. if (nextItem?.Get("done")?.AsBoolean() == false)
  412. {
  413. throw;
  414. }
  415. errors.Add(e.Error);
  416. continue;
  417. }
  418. // note that null here is important
  419. // it will help to detect if all inner promises were rejected
  420. // In F# it would be Option<JsValue>
  421. errors.Add(null!);
  422. var item = promiseResolve.Call(thisObject, new JsValue[] { value });
  423. var thenProps = item.Get("then");
  424. if (thenProps is ICallable thenFunc)
  425. {
  426. var capturedIndex = index;
  427. var alreadyCalled = false;
  428. var onError =
  429. new ClrFunction(_engine, "", (_, args) =>
  430. {
  431. if (!alreadyCalled)
  432. {
  433. alreadyCalled = true;
  434. errors[capturedIndex] = args.At(0);
  435. RejectIfAllRejected();
  436. }
  437. return Undefined;
  438. }, 1, PropertyFlag.Configurable);
  439. thenFunc.Call(item, new JsValue[] { resolveObj, onError });
  440. }
  441. else
  442. {
  443. ExceptionHelper.ThrowTypeError(_realm, "Passed non Promise-like value");
  444. }
  445. index += 1;
  446. } while (true);
  447. }
  448. catch (JavaScriptException e)
  449. {
  450. iterator.Close(CompletionType.Throw);
  451. reject.Call(Undefined, new[] { e.Error });
  452. return resultingPromise;
  453. }
  454. return resultingPromise;
  455. }
  456. // https://tc39.es/ecma262/#sec-promise.race
  457. private JsValue Race(JsValue thisObject, JsValue[] arguments)
  458. {
  459. if (!TryGetPromiseCapabilityAndIterator(thisObject, arguments, "Promise.race", out var capability, out var promiseResolve, out var iterator))
  460. return capability.PromiseInstance;
  461. var (resultingPromise, resolve, reject, _, rejectObj) = capability;
  462. // 7. Let result be PerformPromiseRace(iteratorRecord, C, promiseCapability, promiseResolve).
  463. // https://tc39.es/ecma262/#sec-performpromiserace
  464. try
  465. {
  466. do
  467. {
  468. JsValue nextValue;
  469. try
  470. {
  471. if (!iterator.TryIteratorStep(out var nextItem))
  472. {
  473. break;
  474. }
  475. nextValue = nextItem.Get(CommonProperties.Value);
  476. }
  477. catch (JavaScriptException e)
  478. {
  479. reject.Call(Undefined, new[] { e.Error });
  480. return resultingPromise;
  481. }
  482. // h. Let nextPromise be ? Call(promiseResolve, constructor, « nextValue »).
  483. var nextPromise = promiseResolve.Call(thisObject, new JsValue[] { nextValue });
  484. // i. Perform ? Invoke(nextPromise, "then", « resultCapability.[[Resolve]], resultCapability.[[Reject]] »).
  485. _engine.Invoke(nextPromise, "then", new[] { (JsValue) resolve, rejectObj });
  486. } while (true);
  487. }
  488. catch (JavaScriptException e)
  489. {
  490. // 8. If result is an abrupt completion, then
  491. // a. If iteratorRecord.[[Done]] is false, set result to IteratorClose(iteratorRecord, result).
  492. // b. IfAbruptRejectPromise(result, promiseCapability).
  493. iterator.Close(CompletionType.Throw);
  494. reject.Call(Undefined, new[] { e.Error });
  495. return resultingPromise;
  496. }
  497. // 9. Return Completion(result).
  498. // Note that PerformPromiseRace returns a Promise instance in success case
  499. return resultingPromise;
  500. }
  501. // https://tc39.es/ecma262/#sec-getpromiseresolve
  502. // 27.2.4.1.1 GetPromiseResolve ( promiseConstructor )
  503. // The abstract operation GetPromiseResolve takes argument promiseConstructor. It performs the following steps when called:
  504. //
  505. // 1. Assert: IsConstructor(promiseConstructor) is true.
  506. // 2. Let promiseResolve be ? Get(promiseConstructor, "resolve").
  507. // 3. If IsCallable(promiseResolve) is false, throw a TypeError exception.
  508. // 4. Return promiseResolve.
  509. private ICallable GetPromiseResolve(JsValue promiseConstructor)
  510. {
  511. AssertConstructor(_engine, promiseConstructor);
  512. var resolveProp = promiseConstructor.Get("resolve");
  513. if (resolveProp is ICallable resolve)
  514. {
  515. return resolve;
  516. }
  517. ExceptionHelper.ThrowTypeError(_realm, "resolve is not a function");
  518. // Note: throws right before return
  519. return null;
  520. }
  521. // https://tc39.es/ecma262/#sec-newpromisecapability
  522. // The abstract operation NewPromiseCapability takes argument C.
  523. // It attempts to use C as a constructor in the fashion of the built-in Promise constructor to create a Promise
  524. // object and extract its resolve and reject functions.
  525. // The Promise object plus the resolve and reject functions are used to initialize a new PromiseCapability Record.
  526. // It performs the following steps when called:
  527. //
  528. // 1. If IsConstructor(C) is false, throw a TypeError exception.
  529. // 2. NOTE: C is assumed to be a constructor function that supports the parameter conventions of the Promise constructor (see 27.2.3.1).
  530. // 3. Let promiseCapability be the PromiseCapability Record { [[Promise]]: undefined, [[Resolve]]: undefined, [[Reject]]: undefined }.
  531. // 4. Let steps be the algorithm steps defined in GetCapabilitiesExecutor Functions.
  532. // 5. Let length be the number of non-optional parameters of the function definition in GetCapabilitiesExecutor Functions.
  533. // 6. Let executor be ! CreateBuiltinFunction(steps, length, "", « [[Capability]] »).
  534. // 7. Set executor.[[Capability]] to promiseCapability.
  535. // 8. Let promise be ? Construct(C, « executor »).
  536. // 9. If IsCallable(promiseCapability.[[Resolve]]) is false, throw a TypeError exception.
  537. // 10. If IsCallable(promiseCapability.[[Reject]]) is false, throw a TypeError exception.
  538. // 11. Set promiseCapability.[[Promise]] to promise.
  539. // 12. Return promiseCapability.
  540. internal static PromiseCapability NewPromiseCapability(Engine engine, JsValue c)
  541. {
  542. var ctor = AssertConstructor(engine, c);
  543. JsValue? resolveArg = null;
  544. JsValue? rejectArg = null;
  545. JsValue Executor(JsValue thisObject, JsValue[] arguments)
  546. {
  547. // 25.4.1.5.1 GetCapabilitiesExecutor Functions
  548. // 3. If promiseCapability.[[Resolve]] is not undefined, throw a TypeError exception.
  549. // 4. If promiseCapability.[[Reject]] is not undefined, throw a TypeError exception.
  550. // 5. Set promiseCapability.[[Resolve]] to resolve.
  551. // 6. Set promiseCapability.[[Reject]] to reject.
  552. if (resolveArg is not null && resolveArg != Undefined ||
  553. rejectArg is not null && rejectArg != Undefined)
  554. {
  555. ExceptionHelper.ThrowTypeError(engine.Realm, "executor was already called with not undefined args");
  556. }
  557. resolveArg = arguments.At(0);
  558. rejectArg = arguments.At(1);
  559. return Undefined;
  560. }
  561. var executor = new ClrFunction(engine, "", Executor, 2, PropertyFlag.Configurable);
  562. var instance = ctor.Construct(new JsValue[] { executor }, c);
  563. ICallable? resolve = null;
  564. ICallable? reject = null;
  565. if (resolveArg is ICallable resFunc)
  566. {
  567. resolve = resFunc;
  568. }
  569. else
  570. {
  571. ExceptionHelper.ThrowTypeError(engine.Realm, "resolve is not a function");
  572. }
  573. if (rejectArg is ICallable rejFunc)
  574. {
  575. reject = rejFunc;
  576. }
  577. else
  578. {
  579. ExceptionHelper.ThrowTypeError(engine.Realm, "reject is not a function");
  580. }
  581. return new PromiseCapability(instance, resolve, reject, resolveArg, rejectArg);
  582. }
  583. }
  584. }