PromiseConstructor.cpp 25 KB

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