PromiseConstructor.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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/PromiseCapability.h>
  17. #include <LibJS/Runtime/PromiseConstructor.h>
  18. #include <LibJS/Runtime/PromiseResolvingElementFunctions.h>
  19. namespace JS {
  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, Iterator& 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 Completion(IteratorStep(iteratorRecord)).
  47. auto next_or_error = iterator_step(vm, iterator_record);
  48. // b. If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
  49. // c. ReturnIfAbrupt(next).
  50. if (next_or_error.is_throw_completion()) {
  51. iterator_record.done = true;
  52. return next_or_error.release_error();
  53. }
  54. auto* next = next_or_error.release_value();
  55. // d. If next is false, then
  56. if (!next) {
  57. // i. Set iteratorRecord.[[Done]] to true.
  58. iterator_record.done = true;
  59. // ii. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
  60. // iii. If remainingElementsCount.[[Value]] is 0, then
  61. if (--remaining_elements_count->value == 0) {
  62. // 1-2/3. are handled in `end_of_list`
  63. return TRY(end_of_list(*values));
  64. }
  65. // iv. Return resultCapability.[[Promise]].
  66. return result_capability.promise();
  67. }
  68. // e. Let nextValue be Completion(IteratorValue(next)).
  69. auto next_value_or_error = iterator_value(vm, *next);
  70. // f. If nextValue is an abrupt completion, set iteratorRecord.[[Done]] to true.
  71. // g. ReturnIfAbrupt(nextValue).
  72. if (next_value_or_error.is_throw_completion()) {
  73. iterator_record.done = true;
  74. return next_value_or_error.release_error();
  75. }
  76. auto next_value = next_value_or_error.release_value();
  77. // h. Append undefined to values.
  78. values->values().append(js_undefined());
  79. // i. Let nextPromise be ? Call(promiseResolve, constructor, « nextValue »).
  80. auto next_promise = TRY(call(vm, promise_resolve.as_function(), constructor, next_value));
  81. // j-q. are handled in `invoke_element_function`
  82. // r. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] + 1.
  83. ++remaining_elements_count->value;
  84. // s. Perform ? Invoke(nextPromise, "then", « ... »).
  85. TRY(invoke_element_function(*values, *remaining_elements_count, next_promise, index));
  86. // t. Set index to index + 1.
  87. ++index;
  88. }
  89. }
  90. // 27.2.4.1.2 PerformPromiseAll ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiseall
  91. static ThrowCompletionOr<Value> perform_promise_all(VM& vm, Iterator& iterator_record, Value constructor, PromiseCapability const& result_capability, Value promise_resolve)
  92. {
  93. auto& realm = *vm.current_realm();
  94. return perform_promise_common(
  95. vm, iterator_record, constructor, result_capability, promise_resolve,
  96. [&](PromiseValueList& values) -> ThrowCompletionOr<Value> {
  97. // 1. Let valuesArray be CreateArrayFromList(values).
  98. auto values_array = Array::create_from(realm, values.values());
  99. // 2. Perform ? Call(resultCapability.[[Resolve]], undefined, « valuesArray »).
  100. TRY(call(vm, *result_capability.resolve(), js_undefined(), values_array));
  101. // iv. Return resultCapability.[[Promise]].
  102. return result_capability.promise();
  103. },
  104. [&](PromiseValueList& values, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
  105. // j. Let steps be the algorithm steps defined in Promise.all Resolve Element Functions.
  106. // k. Let length be the number of non-optional parameters of the function definition in Promise.all Resolve Element Functions.
  107. // l. Let onFulfilled be CreateBuiltinFunction(steps, length, "", « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] »).
  108. // m. Set onFulfilled.[[AlreadyCalled]] to false.
  109. // n. Set onFulfilled.[[Index]] to index.
  110. // o. Set onFulfilled.[[Values]] to values.
  111. // p. Set onFulfilled.[[Capability]] to resultCapability.
  112. // q. Set onFulfilled.[[RemainingElements]] to remainingElementsCount.
  113. auto* on_fulfilled = PromiseAllResolveElementFunction::create(realm, index, values, result_capability, remaining_elements_count);
  114. on_fulfilled->define_direct_property(vm.names.name, PrimitiveString::create(vm, DeprecatedString::empty()), Attribute::Configurable);
  115. // s. Perform ? Invoke(nextPromise, "then", « onFulfilled, resultCapability.[[Reject]] »).
  116. return next_promise.invoke(vm, vm.names.then, on_fulfilled, result_capability.reject());
  117. });
  118. }
  119. // 27.2.4.2.1 PerformPromiseAllSettled ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiseallsettled
  120. static ThrowCompletionOr<Value> perform_promise_all_settled(VM& vm, Iterator& iterator_record, Value constructor, PromiseCapability const& result_capability, Value promise_resolve)
  121. {
  122. auto& realm = *vm.current_realm();
  123. return perform_promise_common(
  124. vm, iterator_record, constructor, result_capability, promise_resolve,
  125. [&](PromiseValueList& values) -> ThrowCompletionOr<Value> {
  126. auto values_array = Array::create_from(realm, values.values());
  127. TRY(call(vm, *result_capability.resolve(), js_undefined(), values_array));
  128. return result_capability.promise();
  129. },
  130. [&](PromiseValueList& values, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
  131. // j. Let stepsFulfilled be the algorithm steps defined in Promise.allSettled Resolve Element Functions.
  132. // k. Let lengthFulfilled be the number of non-optional parameters of the function definition in Promise.allSettled Resolve Element Functions.
  133. // l. Let onFulfilled be CreateBuiltinFunction(stepsFulfilled, lengthFulfilled, "", « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] »).
  134. // m. Let alreadyCalled be the Record { [[Value]]: false }.
  135. // n. Set onFulfilled.[[AlreadyCalled]] to alreadyCalled.
  136. // o. Set onFulfilled.[[Index]] to index.
  137. // p. Set onFulfilled.[[Values]] to values.
  138. // q. Set onFulfilled.[[Capability]] to resultCapability.
  139. // r. Set onFulfilled.[[RemainingElements]] to remainingElementsCount.
  140. auto* on_fulfilled = PromiseAllSettledResolveElementFunction::create(realm, index, values, result_capability, remaining_elements_count);
  141. on_fulfilled->define_direct_property(vm.names.name, PrimitiveString::create(vm, DeprecatedString::empty()), Attribute::Configurable);
  142. // s. Let stepsRejected be the algorithm steps defined in Promise.allSettled Reject Element Functions.
  143. // t. Let lengthRejected be the number of non-optional parameters of the function definition in Promise.allSettled Reject Element Functions.
  144. // u. Let onRejected be CreateBuiltinFunction(stepsRejected, lengthRejected, "", « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] »).
  145. // v. Set onRejected.[[AlreadyCalled]] to alreadyCalled.
  146. // w. Set onRejected.[[Index]] to index.
  147. // x. Set onRejected.[[Values]] to values.
  148. // y. Set onRejected.[[Capability]] to resultCapability.
  149. // z. Set onRejected.[[RemainingElements]] to remainingElementsCount.
  150. auto* on_rejected = PromiseAllSettledRejectElementFunction::create(realm, index, values, result_capability, remaining_elements_count);
  151. on_rejected->define_direct_property(vm.names.name, PrimitiveString::create(vm, DeprecatedString::empty()), Attribute::Configurable);
  152. // ab. Perform ? Invoke(nextPromise, "then", « onFulfilled, onRejected »).
  153. return next_promise.invoke(vm, vm.names.then, on_fulfilled, on_rejected);
  154. });
  155. }
  156. // 27.2.4.3.1 PerformPromiseAny ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiseany
  157. static ThrowCompletionOr<Value> perform_promise_any(VM& vm, Iterator& iterator_record, Value constructor, PromiseCapability const& result_capability, Value promise_resolve)
  158. {
  159. auto& realm = *vm.current_realm();
  160. return perform_promise_common(
  161. vm, iterator_record, constructor, result_capability, promise_resolve,
  162. [&](PromiseValueList& errors) -> ThrowCompletionOr<Value> {
  163. // 1. Let error be a newly created AggregateError object.
  164. auto error = AggregateError::create(realm);
  165. // 2. Perform ! DefinePropertyOrThrow(error, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: CreateArrayFromList(errors) }).
  166. auto errors_array = Array::create_from(realm, errors.values());
  167. MUST(error->define_property_or_throw(vm.names.errors, { .value = errors_array, .writable = true, .enumerable = false, .configurable = true }));
  168. // 3. Return ThrowCompletion(error).
  169. return throw_completion(error);
  170. },
  171. [&](PromiseValueList& errors, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
  172. // j. Let stepsRejected be the algorithm steps defined in Promise.any Reject Element Functions.
  173. // k. Let lengthRejected be the number of non-optional parameters of the function definition in Promise.any Reject Element Functions.
  174. // l. Let onRejected be CreateBuiltinFunction(stepsRejected, lengthRejected, "", « [[AlreadyCalled]], [[Index]], [[Errors]], [[Capability]], [[RemainingElements]] »).
  175. // m. Set onRejected.[[AlreadyCalled]] to false.
  176. // n. Set onRejected.[[Index]] to index.
  177. // o. Set onRejected.[[Errors]] to errors.
  178. // p. Set onRejected.[[Capability]] to resultCapability.
  179. // q. Set onRejected.[[RemainingElements]] to remainingElementsCount.
  180. auto* on_rejected = PromiseAnyRejectElementFunction::create(realm, index, errors, result_capability, remaining_elements_count);
  181. on_rejected->define_direct_property(vm.names.name, PrimitiveString::create(vm, DeprecatedString::empty()), Attribute::Configurable);
  182. // s. Perform ? Invoke(nextPromise, "then", « resultCapability.[[Resolve]], onRejected »).
  183. return next_promise.invoke(vm, vm.names.then, result_capability.resolve(), on_rejected);
  184. });
  185. }
  186. // 27.2.4.5.1 PerformPromiseRace ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiserace
  187. static ThrowCompletionOr<Value> perform_promise_race(VM& vm, Iterator& iterator_record, Value constructor, PromiseCapability const& result_capability, Value promise_resolve)
  188. {
  189. return perform_promise_common(
  190. vm, iterator_record, constructor, result_capability, promise_resolve,
  191. [&](PromiseValueList&) -> ThrowCompletionOr<Value> {
  192. // ii. Return resultCapability.[[Promise]].
  193. return result_capability.promise();
  194. },
  195. [&](PromiseValueList&, RemainingElements&, Value next_promise, size_t) {
  196. // i. Perform ? Invoke(nextPromise, "then", « resultCapability.[[Resolve]], resultCapability.[[Reject]] »).
  197. return next_promise.invoke(vm, vm.names.then, result_capability.resolve(), result_capability.reject());
  198. });
  199. }
  200. PromiseConstructor::PromiseConstructor(Realm& realm)
  201. : NativeFunction(realm.vm().names.Promise.as_string(), *realm.intrinsics().function_prototype())
  202. {
  203. }
  204. void PromiseConstructor::initialize(Realm& realm)
  205. {
  206. auto& vm = this->vm();
  207. NativeFunction::initialize(realm);
  208. // 27.2.4.4 Promise.prototype, https://tc39.es/ecma262/#sec-promise.prototype
  209. define_direct_property(vm.names.prototype, realm.intrinsics().promise_prototype(), 0);
  210. u8 attr = Attribute::Writable | Attribute::Configurable;
  211. define_native_function(realm, vm.names.all, all, 1, attr);
  212. define_native_function(realm, vm.names.allSettled, all_settled, 1, attr);
  213. define_native_function(realm, vm.names.any, any, 1, attr);
  214. define_native_function(realm, vm.names.race, race, 1, attr);
  215. define_native_function(realm, vm.names.reject, reject, 1, attr);
  216. define_native_function(realm, vm.names.resolve, resolve, 1, 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<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)).
  264. // 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  265. auto iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(vm, vm.argument(0)));
  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)).
  290. // 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  291. auto iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(vm, vm.argument(0)));
  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)).
  316. // 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  317. auto iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(vm, vm.argument(0)));
  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)).
  342. // 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  343. auto iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(vm, vm.argument(0)));
  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. }