PromiseConstructor.cs 27 KB

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