PromiseConstructor.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. /*
  2. * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Function.h>
  7. #include <LibJS/Runtime/AbstractOperations.h>
  8. #include <LibJS/Runtime/AggregateError.h>
  9. #include <LibJS/Runtime/Array.h>
  10. #include <LibJS/Runtime/Error.h>
  11. #include <LibJS/Runtime/FunctionObject.h>
  12. #include <LibJS/Runtime/GlobalObject.h>
  13. #include <LibJS/Runtime/Iterator.h>
  14. #include <LibJS/Runtime/Promise.h>
  15. #include <LibJS/Runtime/PromiseCapability.h>
  16. #include <LibJS/Runtime/PromiseConstructor.h>
  17. #include <LibJS/Runtime/PromiseResolvingElementFunctions.h>
  18. namespace JS {
  19. // 27.2.4.1.1 GetPromiseResolve ( promiseConstructor ), https://tc39.es/ecma262/#sec-getpromiseresolve
  20. static ThrowCompletionOr<Value> get_promise_resolve(VM& vm, Value constructor)
  21. {
  22. VERIFY(constructor.is_constructor());
  23. // 1. Let promiseResolve be ? Get(promiseConstructor, "resolve").
  24. auto promise_resolve = TRY(constructor.get(vm, vm.names.resolve));
  25. // 2. If IsCallable(promiseResolve) is false, throw a TypeError exception.
  26. if (!promise_resolve.is_function())
  27. return vm.throw_completion<TypeError>(ErrorType::NotAFunction, promise_resolve.to_string_without_side_effects());
  28. // 3. Return promiseResolve.
  29. return promise_resolve;
  30. }
  31. using EndOfElementsCallback = Function<ThrowCompletionOr<Value>(PromiseValueList&)>;
  32. using InvokeElementFunctionCallback = Function<ThrowCompletionOr<Value>(PromiseValueList&, RemainingElements&, Value, size_t)>;
  33. static ThrowCompletionOr<Value> perform_promise_common(VM& vm, IteratorRecord& iterator_record, Value constructor, PromiseCapability const& result_capability, Value promise_resolve, EndOfElementsCallback end_of_list, InvokeElementFunctionCallback invoke_element_function)
  34. {
  35. VERIFY(constructor.is_constructor());
  36. VERIFY(promise_resolve.is_function());
  37. // 1. Let values be a new empty List.
  38. auto values = vm.heap().allocate_without_realm<PromiseValueList>();
  39. // 2. Let remainingElementsCount be the Record { [[Value]]: 1 }.
  40. auto remaining_elements_count = vm.heap().allocate_without_realm<RemainingElements>(1);
  41. // 3. Let index be 0.
  42. size_t index = 0;
  43. // 4. Repeat,
  44. while (true) {
  45. // a. Let next be Completion(IteratorStep(iteratorRecord)).
  46. auto next_or_error = iterator_step(vm, iterator_record);
  47. // b. If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
  48. // c. ReturnIfAbrupt(next).
  49. if (next_or_error.is_throw_completion()) {
  50. iterator_record.done = true;
  51. return next_or_error.release_error();
  52. }
  53. auto next = next_or_error.release_value();
  54. // d. If next is false, then
  55. if (!next) {
  56. // i. Set iteratorRecord.[[Done]] to true.
  57. iterator_record.done = true;
  58. // ii. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
  59. // iii. If remainingElementsCount.[[Value]] is 0, then
  60. if (--remaining_elements_count->value == 0) {
  61. // 1-2/3. are handled in `end_of_list`
  62. return TRY(end_of_list(*values));
  63. }
  64. // iv. Return resultCapability.[[Promise]].
  65. return result_capability.promise();
  66. }
  67. // e. Let nextValue be Completion(IteratorValue(next)).
  68. auto next_value_or_error = iterator_value(vm, *next);
  69. // f. If nextValue is an abrupt completion, set iteratorRecord.[[Done]] to true.
  70. // g. ReturnIfAbrupt(nextValue).
  71. if (next_value_or_error.is_throw_completion()) {
  72. iterator_record.done = true;
  73. return next_value_or_error.release_error();
  74. }
  75. auto next_value = next_value_or_error.release_value();
  76. // h. Append undefined to values.
  77. values->values().append(js_undefined());
  78. // i. Let nextPromise be ? Call(promiseResolve, constructor, « nextValue »).
  79. auto next_promise = TRY(call(vm, promise_resolve.as_function(), constructor, next_value));
  80. // j-q. are handled in `invoke_element_function`
  81. // r. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] + 1.
  82. ++remaining_elements_count->value;
  83. // s. Perform ? Invoke(nextPromise, "then", « ... »).
  84. TRY(invoke_element_function(*values, *remaining_elements_count, next_promise, index));
  85. // t. Set index to index + 1.
  86. ++index;
  87. }
  88. }
  89. // 27.2.4.1.2 PerformPromiseAll ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiseall
  90. static ThrowCompletionOr<Value> perform_promise_all(VM& vm, IteratorRecord& iterator_record, Value constructor, PromiseCapability const& result_capability, Value promise_resolve)
  91. {
  92. auto& realm = *vm.current_realm();
  93. return perform_promise_common(
  94. vm, iterator_record, constructor, result_capability, promise_resolve,
  95. [&](PromiseValueList& values) -> ThrowCompletionOr<Value> {
  96. // 1. Let valuesArray be CreateArrayFromList(values).
  97. auto values_array = Array::create_from(realm, values.values());
  98. // 2. Perform ? Call(resultCapability.[[Resolve]], undefined, « valuesArray »).
  99. TRY(call(vm, *result_capability.resolve(), js_undefined(), values_array));
  100. // iv. Return resultCapability.[[Promise]].
  101. return result_capability.promise();
  102. },
  103. [&](PromiseValueList& values, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
  104. // j. Let steps be the algorithm steps defined in Promise.all Resolve Element Functions.
  105. // k. Let length be the number of non-optional parameters of the function definition in Promise.all Resolve Element Functions.
  106. // l. Let onFulfilled be CreateBuiltinFunction(steps, length, "", « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] »).
  107. // m. Set onFulfilled.[[AlreadyCalled]] to false.
  108. // n. Set onFulfilled.[[Index]] to index.
  109. // o. Set onFulfilled.[[Values]] to values.
  110. // p. Set onFulfilled.[[Capability]] to resultCapability.
  111. // q. Set onFulfilled.[[RemainingElements]] to remainingElementsCount.
  112. auto on_fulfilled = PromiseAllResolveElementFunction::create(realm, index, values, result_capability, remaining_elements_count);
  113. on_fulfilled->define_direct_property(vm.names.name, PrimitiveString::create(vm, String {}), Attribute::Configurable);
  114. // s. Perform ? Invoke(nextPromise, "then", « onFulfilled, resultCapability.[[Reject]] »).
  115. return next_promise.invoke(vm, vm.names.then, on_fulfilled, result_capability.reject());
  116. });
  117. }
  118. // 27.2.4.2.1 PerformPromiseAllSettled ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiseallsettled
  119. static ThrowCompletionOr<Value> perform_promise_all_settled(VM& vm, IteratorRecord& iterator_record, Value constructor, PromiseCapability const& result_capability, Value promise_resolve)
  120. {
  121. auto& realm = *vm.current_realm();
  122. return perform_promise_common(
  123. vm, iterator_record, constructor, result_capability, promise_resolve,
  124. [&](PromiseValueList& values) -> ThrowCompletionOr<Value> {
  125. auto values_array = Array::create_from(realm, values.values());
  126. TRY(call(vm, *result_capability.resolve(), js_undefined(), values_array));
  127. return result_capability.promise();
  128. },
  129. [&](PromiseValueList& values, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
  130. // j. Let stepsFulfilled be the algorithm steps defined in Promise.allSettled Resolve Element Functions.
  131. // k. Let lengthFulfilled be the number of non-optional parameters of the function definition in Promise.allSettled Resolve Element Functions.
  132. // l. Let onFulfilled be CreateBuiltinFunction(stepsFulfilled, lengthFulfilled, "", « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] »).
  133. // m. Let alreadyCalled be the Record { [[Value]]: false }.
  134. // n. Set onFulfilled.[[AlreadyCalled]] to alreadyCalled.
  135. // o. Set onFulfilled.[[Index]] to index.
  136. // p. Set onFulfilled.[[Values]] to values.
  137. // q. Set onFulfilled.[[Capability]] to resultCapability.
  138. // r. Set onFulfilled.[[RemainingElements]] to remainingElementsCount.
  139. auto on_fulfilled = PromiseAllSettledResolveElementFunction::create(realm, index, values, result_capability, remaining_elements_count);
  140. on_fulfilled->define_direct_property(vm.names.name, PrimitiveString::create(vm, String {}), Attribute::Configurable);
  141. // s. Let stepsRejected be the algorithm steps defined in Promise.allSettled Reject Element Functions.
  142. // t. Let lengthRejected be the number of non-optional parameters of the function definition in Promise.allSettled Reject Element Functions.
  143. // u. Let onRejected be CreateBuiltinFunction(stepsRejected, lengthRejected, "", « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] »).
  144. // v. Set onRejected.[[AlreadyCalled]] to alreadyCalled.
  145. // w. Set onRejected.[[Index]] to index.
  146. // x. Set onRejected.[[Values]] to values.
  147. // y. Set onRejected.[[Capability]] to resultCapability.
  148. // z. Set onRejected.[[RemainingElements]] to remainingElementsCount.
  149. auto on_rejected = PromiseAllSettledRejectElementFunction::create(realm, index, values, result_capability, remaining_elements_count);
  150. on_rejected->define_direct_property(vm.names.name, PrimitiveString::create(vm, String {}), Attribute::Configurable);
  151. // ab. Perform ? Invoke(nextPromise, "then", « onFulfilled, onRejected »).
  152. return next_promise.invoke(vm, vm.names.then, on_fulfilled, on_rejected);
  153. });
  154. }
  155. // 27.2.4.3.1 PerformPromiseAny ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiseany
  156. static ThrowCompletionOr<Value> perform_promise_any(VM& vm, IteratorRecord& iterator_record, Value constructor, PromiseCapability& result_capability, Value promise_resolve)
  157. {
  158. auto& realm = *vm.current_realm();
  159. return perform_promise_common(
  160. vm, iterator_record, constructor, result_capability, promise_resolve,
  161. [&](PromiseValueList& errors) -> ThrowCompletionOr<Value> {
  162. // 1. Let error be a newly created AggregateError object.
  163. auto error = AggregateError::create(realm);
  164. // 2. Perform ! DefinePropertyOrThrow(error, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: CreateArrayFromList(errors) }).
  165. auto errors_array = Array::create_from(realm, errors.values());
  166. MUST(error->define_property_or_throw(vm.names.errors, { .value = errors_array, .writable = true, .enumerable = false, .configurable = true }));
  167. // 3. Return ThrowCompletion(error).
  168. return throw_completion(error);
  169. },
  170. [&](PromiseValueList& errors, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
  171. // j. Let stepsRejected be the algorithm steps defined in Promise.any Reject Element Functions.
  172. // k. Let lengthRejected be the number of non-optional parameters of the function definition in Promise.any Reject Element Functions.
  173. // l. Let onRejected be CreateBuiltinFunction(stepsRejected, lengthRejected, "", « [[AlreadyCalled]], [[Index]], [[Errors]], [[Capability]], [[RemainingElements]] »).
  174. // m. Set onRejected.[[AlreadyCalled]] to false.
  175. // n. Set onRejected.[[Index]] to index.
  176. // o. Set onRejected.[[Errors]] to errors.
  177. // p. Set onRejected.[[Capability]] to resultCapability.
  178. // q. Set onRejected.[[RemainingElements]] to remainingElementsCount.
  179. auto on_rejected = PromiseAnyRejectElementFunction::create(realm, index, errors, result_capability, remaining_elements_count);
  180. on_rejected->define_direct_property(vm.names.name, PrimitiveString::create(vm, String {}), Attribute::Configurable);
  181. // s. Perform ? Invoke(nextPromise, "then", « resultCapability.[[Resolve]], onRejected »).
  182. return next_promise.invoke(vm, vm.names.then, result_capability.resolve(), on_rejected);
  183. });
  184. }
  185. // 27.2.4.5.1 PerformPromiseRace ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiserace
  186. static ThrowCompletionOr<Value> perform_promise_race(VM& vm, IteratorRecord& iterator_record, Value constructor, PromiseCapability const& result_capability, Value promise_resolve)
  187. {
  188. return perform_promise_common(
  189. vm, iterator_record, constructor, result_capability, promise_resolve,
  190. [&](PromiseValueList&) -> ThrowCompletionOr<Value> {
  191. // ii. Return resultCapability.[[Promise]].
  192. return result_capability.promise();
  193. },
  194. [&](PromiseValueList&, RemainingElements&, Value next_promise, size_t) {
  195. // i. Perform ? Invoke(nextPromise, "then", « resultCapability.[[Resolve]], resultCapability.[[Reject]] »).
  196. return next_promise.invoke(vm, vm.names.then, result_capability.resolve(), result_capability.reject());
  197. });
  198. }
  199. PromiseConstructor::PromiseConstructor(Realm& realm)
  200. : NativeFunction(realm.vm().names.Promise.as_string(), realm.intrinsics().function_prototype())
  201. {
  202. }
  203. void PromiseConstructor::initialize(Realm& realm)
  204. {
  205. auto& vm = this->vm();
  206. Base::initialize(realm);
  207. // 27.2.4.4 Promise.prototype, https://tc39.es/ecma262/#sec-promise.prototype
  208. define_direct_property(vm.names.prototype, realm.intrinsics().promise_prototype(), 0);
  209. u8 attr = Attribute::Writable | Attribute::Configurable;
  210. define_native_function(realm, vm.names.all, all, 1, attr);
  211. define_native_function(realm, vm.names.allSettled, all_settled, 1, attr);
  212. define_native_function(realm, vm.names.any, any, 1, attr);
  213. define_native_function(realm, vm.names.race, race, 1, attr);
  214. define_native_function(realm, vm.names.reject, reject, 1, attr);
  215. define_native_function(realm, vm.names.resolve, resolve, 1, attr);
  216. define_native_function(realm, vm.names.withResolvers, with_resolvers, 0, attr);
  217. define_native_accessor(realm, vm.well_known_symbol_species(), symbol_species_getter, {}, Attribute::Configurable);
  218. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  219. }
  220. // 27.2.3.1 Promise ( executor ), https://tc39.es/ecma262/#sec-promise-executor
  221. ThrowCompletionOr<Value> PromiseConstructor::call()
  222. {
  223. auto& vm = this->vm();
  224. // 1. If NewTarget is undefined, throw a TypeError exception.
  225. return vm.throw_completion<TypeError>(ErrorType::ConstructorWithoutNew, vm.names.Promise);
  226. }
  227. // 27.2.3.1 Promise ( executor ), https://tc39.es/ecma262/#sec-promise-executor
  228. ThrowCompletionOr<NonnullGCPtr<Object>> PromiseConstructor::construct(FunctionObject& new_target)
  229. {
  230. auto& vm = this->vm();
  231. auto executor = vm.argument(0);
  232. // 2. If IsCallable(executor) is false, throw a TypeError exception.
  233. if (!executor.is_function())
  234. return vm.throw_completion<TypeError>(ErrorType::PromiseExecutorNotAFunction);
  235. // 3. Let promise be ? OrdinaryCreateFromConstructor(NewTarget, "%Promise.prototype%", « [[PromiseState]], [[PromiseResult]], [[PromiseFulfillReactions]], [[PromiseRejectReactions]], [[PromiseIsHandled]] »).
  236. // 4. Set promise.[[PromiseState]] to pending.
  237. // 5. Set promise.[[PromiseFulfillReactions]] to a new empty List.
  238. // 6. Set promise.[[PromiseRejectReactions]] to a new empty List.
  239. // 7. Set promise.[[PromiseIsHandled]] to false.
  240. auto promise = TRY(ordinary_create_from_constructor<Promise>(vm, new_target, &Intrinsics::promise_prototype));
  241. // 8. Let resolvingFunctions be CreateResolvingFunctions(promise).
  242. auto [resolve_function, reject_function] = promise->create_resolving_functions();
  243. // 9. Let completion be Completion(Call(executor, undefined, « resolvingFunctions.[[Resolve]], resolvingFunctions.[[Reject]] »)).
  244. auto completion = JS::call(vm, executor.as_function(), js_undefined(), resolve_function, reject_function);
  245. // 10. If completion is an abrupt completion, then
  246. if (completion.is_error()) {
  247. // a. Perform ? Call(resolvingFunctions.[[Reject]], undefined, « completion.[[Value]] »).
  248. TRY(JS::call(vm, *reject_function, js_undefined(), *completion.release_error().value()));
  249. }
  250. // 11. Return promise.
  251. return promise;
  252. }
  253. // 27.2.4.1 Promise.all ( iterable ), https://tc39.es/ecma262/#sec-promise.all
  254. JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::all)
  255. {
  256. // 1. Let C be the this value.
  257. auto constructor = TRY(vm.this_value().to_object(vm));
  258. // 2. Let promiseCapability be ? NewPromiseCapability(C).
  259. auto promise_capability = TRY(new_promise_capability(vm, constructor));
  260. // 3. Let promiseResolve be Completion(GetPromiseResolve(C)).
  261. // 4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  262. auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(vm, constructor));
  263. // 5. Let iteratorRecord be Completion(GetIterator(iterable, sync)).
  264. // 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  265. auto iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(vm, vm.argument(0), IteratorHint::Sync));
  266. // 7. Let result be Completion(PerformPromiseAll(iteratorRecord, C, promiseCapability, promiseResolve)).
  267. auto result = perform_promise_all(vm, iterator_record, constructor, promise_capability, promise_resolve);
  268. // 8. If result is an abrupt completion, then
  269. if (result.is_error()) {
  270. // a. If iteratorRecord.[[Done]] is false, set result to Completion(IteratorClose(iteratorRecord, result)).
  271. if (!iterator_record.done)
  272. result = iterator_close(vm, iterator_record, result.release_error());
  273. // b. IfAbruptRejectPromise(result, promiseCapability).
  274. TRY_OR_REJECT(vm, promise_capability, result);
  275. }
  276. // 9. Return ? result.
  277. return result;
  278. }
  279. // 27.2.4.2 Promise.allSettled ( iterable ), https://tc39.es/ecma262/#sec-promise.allsettled
  280. JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::all_settled)
  281. {
  282. // 1. Let C be the this value.
  283. auto constructor = TRY(vm.this_value().to_object(vm));
  284. // 2. Let promiseCapability be ? NewPromiseCapability(C).
  285. auto promise_capability = TRY(new_promise_capability(vm, constructor));
  286. // 3. Let promiseResolve be Completion(GetPromiseResolve(C)).
  287. // 4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  288. auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(vm, constructor));
  289. // 5. Let iteratorRecord be Completion(GetIterator(iterable, sync)).
  290. // 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  291. auto iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(vm, vm.argument(0), IteratorHint::Sync));
  292. // 7. Let result be Completion(PerformPromiseAllSettled(iteratorRecord, C, promiseCapability, promiseResolve)).
  293. auto result = perform_promise_all_settled(vm, iterator_record, constructor, promise_capability, promise_resolve);
  294. // 8. If result is an abrupt completion, then
  295. if (result.is_error()) {
  296. // a. If iteratorRecord.[[Done]] is false, set result to Completion(IteratorClose(iteratorRecord, result)).
  297. if (!iterator_record.done)
  298. result = iterator_close(vm, iterator_record, result.release_error());
  299. // b. IfAbruptRejectPromise(result, promiseCapability).
  300. TRY_OR_REJECT(vm, promise_capability, result);
  301. }
  302. // 9. Return ? result.
  303. return result;
  304. }
  305. // 27.2.4.3 Promise.any ( iterable ), https://tc39.es/ecma262/#sec-promise.any
  306. JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::any)
  307. {
  308. // 1. Let C be the this value.
  309. auto constructor = TRY(vm.this_value().to_object(vm));
  310. // 2. Let promiseCapability be ? NewPromiseCapability(C).
  311. auto promise_capability = TRY(new_promise_capability(vm, constructor));
  312. // 3. Let promiseResolve be Completion(GetPromiseResolve(C)).
  313. // 4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  314. auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(vm, constructor));
  315. // 5. Let iteratorRecord be Completion(GetIterator(iterable, sync)).
  316. // 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  317. auto iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(vm, vm.argument(0), IteratorHint::Sync));
  318. // 7. Let result be Completion(PerformPromiseAny(iteratorRecord, C, promiseCapability, promiseResolve)).
  319. auto result = perform_promise_any(vm, iterator_record, constructor, promise_capability, promise_resolve);
  320. // 8. If result is an abrupt completion, then
  321. if (result.is_error()) {
  322. // a. If iteratorRecord.[[Done]] is false, set result to Completion(IteratorClose(iteratorRecord, result)).
  323. if (!iterator_record.done)
  324. result = iterator_close(vm, iterator_record, result.release_error());
  325. // b. IfAbruptRejectPromise(result, promiseCapability).
  326. TRY_OR_REJECT(vm, promise_capability, result);
  327. }
  328. // 9. Return ? result.
  329. return result;
  330. }
  331. // 27.2.4.5 Promise.race ( iterable ), https://tc39.es/ecma262/#sec-promise.race
  332. JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::race)
  333. {
  334. // 1. Let C be the this value.
  335. auto constructor = TRY(vm.this_value().to_object(vm));
  336. // 2. Let promiseCapability be ? NewPromiseCapability(C).
  337. auto promise_capability = TRY(new_promise_capability(vm, constructor));
  338. // 3. Let promiseResolve be Completion(GetPromiseResolve(C)).
  339. // 4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  340. auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(vm, constructor));
  341. // 5. Let iteratorRecord be Completion(GetIterator(iterable, sync)).
  342. // 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  343. auto iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(vm, vm.argument(0), IteratorHint::Sync));
  344. // 7. Let result be Completion(PerformPromiseRace(iteratorRecord, C, promiseCapability, promiseResolve)).
  345. auto result = perform_promise_race(vm, iterator_record, constructor, promise_capability, promise_resolve);
  346. // 8. If result is an abrupt completion, then
  347. if (result.is_error()) {
  348. // a. If iteratorRecord.[[Done]] is false, set result to Completion(IteratorClose(iteratorRecord, result)).
  349. if (!iterator_record.done)
  350. result = iterator_close(vm, iterator_record, result.release_error());
  351. // b. IfAbruptRejectPromise(result, promiseCapability).
  352. TRY_OR_REJECT(vm, promise_capability, result);
  353. }
  354. // 9. Return ? result.
  355. return result;
  356. }
  357. // 27.2.4.6 Promise.reject ( r ), https://tc39.es/ecma262/#sec-promise.reject
  358. JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::reject)
  359. {
  360. auto reason = vm.argument(0);
  361. // 1. Let C be the this value.
  362. auto constructor = TRY(vm.this_value().to_object(vm));
  363. // 2. Let promiseCapability be ? NewPromiseCapability(C).
  364. auto promise_capability = TRY(new_promise_capability(vm, constructor));
  365. // 3. Perform ? Call(promiseCapability.[[Reject]], undefined, « r »).
  366. [[maybe_unused]] auto result = TRY(JS::call(vm, *promise_capability->reject(), js_undefined(), reason));
  367. // 4. Return promiseCapability.[[Promise]].
  368. return promise_capability->promise();
  369. }
  370. // 27.2.4.7 Promise.resolve ( x ), https://tc39.es/ecma262/#sec-promise.resolve
  371. JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::resolve)
  372. {
  373. auto value = vm.argument(0);
  374. // 1. Let C be the this value.
  375. auto constructor = vm.this_value();
  376. // 2. If Type(C) is not Object, throw a TypeError exception.
  377. if (!constructor.is_object())
  378. return vm.throw_completion<TypeError>(ErrorType::NotAnObject, constructor.to_string_without_side_effects());
  379. // 3. Return ? PromiseResolve(C, x).
  380. return TRY(promise_resolve(vm, constructor.as_object(), value));
  381. }
  382. // 27.2.4.8 get Promise [ @@species ], https://tc39.es/ecma262/#sec-get-promise-@@species
  383. JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::symbol_species_getter)
  384. {
  385. // 1. Return the this value.
  386. return vm.this_value();
  387. }
  388. // 1.1.1.1 Promise.withResolvers ( ), https://tc39.es/proposal-promise-with-resolvers/#sec-promise.withResolvers
  389. JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::with_resolvers)
  390. {
  391. auto& realm = *vm.current_realm();
  392. // 1. Let C be the this value.
  393. auto constructor = vm.this_value();
  394. // 2. Let promiseCapability be ? NewPromiseCapability(C).
  395. auto promise_capability = TRY(new_promise_capability(vm, constructor));
  396. // 3. Let obj be OrdinaryObjectCreate(%Object.prototype%).
  397. auto object = Object::create(realm, realm.intrinsics().object_prototype());
  398. // 4. Perform ! CreateDataPropertyOrThrow(obj, "promise", promiseCapability.[[Promise]]).
  399. MUST(object->create_data_property_or_throw(vm.names.promise, promise_capability->promise()));
  400. // 5. Perform ! CreateDataPropertyOrThrow(obj, "resolve", promiseCapability.[[Resolve]]).
  401. MUST(object->create_data_property_or_throw(vm.names.resolve, promise_capability->resolve()));
  402. // 6. Perform ! CreateDataPropertyOrThrow(obj, "reject", promiseCapability.[[Reject]]).
  403. MUST(object->create_data_property_or_throw(vm.names.reject, promise_capability->reject()));
  404. // 7. Return obj.
  405. return object;
  406. }
  407. }