PromiseConstructor.cs 26 KB

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