PromiseConstructor.cs 28 KB

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