PromiseConstructor.cpp 24 KB

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