PromiseConstructor.cs 27 KB

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