Promise.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. /*
  2. * Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Function.h>
  7. #include <AK/TypeCasts.h>
  8. #include <LibJS/Heap/HeapFunction.h>
  9. #include <LibJS/Runtime/PromiseCapability.h>
  10. #include <LibJS/Runtime/PromiseConstructor.h>
  11. #include <LibJS/Runtime/Realm.h>
  12. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  13. #include <LibWeb/Bindings/HostDefined.h>
  14. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  15. #include <LibWeb/WebIDL/ExceptionOr.h>
  16. #include <LibWeb/WebIDL/Promise.h>
  17. namespace Web::WebIDL {
  18. // https://webidl.spec.whatwg.org/#a-new-promise
  19. JS::NonnullGCPtr<Promise> create_promise(JS::Realm& realm)
  20. {
  21. auto& vm = realm.vm();
  22. // 1. Let constructor be realm.[[Intrinsics]].[[%Promise%]].
  23. auto constructor = realm.intrinsics().promise_constructor();
  24. // Return ? NewPromiseCapability(constructor).
  25. // NOTE: When called with %Promise%, NewPromiseCapability can't throw.
  26. return MUST(JS::new_promise_capability(vm, constructor));
  27. }
  28. // https://webidl.spec.whatwg.org/#a-promise-resolved-with
  29. JS::NonnullGCPtr<Promise> create_resolved_promise(JS::Realm& realm, JS::Value value)
  30. {
  31. auto& vm = realm.vm();
  32. // 1. Let value be the result of converting x to an ECMAScript value.
  33. // 2. Let constructor be realm.[[Intrinsics]].[[%Promise%]].
  34. auto constructor = realm.intrinsics().promise_constructor();
  35. // 3. Let promiseCapability be ? NewPromiseCapability(constructor).
  36. // NOTE: When called with %Promise%, NewPromiseCapability can't throw.
  37. auto promise_capability = MUST(JS::new_promise_capability(vm, constructor));
  38. // 4. Perform ! Call(promiseCapability.[[Resolve]], undefined, « value »).
  39. MUST(JS::call(vm, *promise_capability->resolve(), JS::js_undefined(), value));
  40. // 5. Return promiseCapability.
  41. return promise_capability;
  42. }
  43. // https://webidl.spec.whatwg.org/#a-promise-rejected-with
  44. JS::NonnullGCPtr<Promise> create_rejected_promise(JS::Realm& realm, JS::Value reason)
  45. {
  46. auto& vm = realm.vm();
  47. // 1. Let constructor be realm.[[Intrinsics]].[[%Promise%]].
  48. auto constructor = realm.intrinsics().promise_constructor();
  49. // 2. Let promiseCapability be ? NewPromiseCapability(constructor).
  50. // NOTE: When called with %Promise%, NewPromiseCapability can't throw.
  51. auto promise_capability = MUST(JS::new_promise_capability(vm, constructor));
  52. // 3. Perform ! Call(promiseCapability.[[Reject]], undefined, « r »).
  53. MUST(JS::call(vm, *promise_capability->reject(), JS::js_undefined(), reason));
  54. // 4. Return promiseCapability.
  55. return promise_capability;
  56. }
  57. // https://webidl.spec.whatwg.org/#resolve
  58. void resolve_promise(JS::Realm& realm, Promise const& promise, JS::Value value)
  59. {
  60. auto& vm = realm.vm();
  61. // 1. If x is not given, then let it be the undefined value.
  62. // NOTE: This is done via the default argument.
  63. // 2. Let value be the result of converting x to an ECMAScript value.
  64. // 3. Perform ! Call(p.[[Resolve]], undefined, « value »).
  65. MUST(JS::call(vm, *promise.resolve(), JS::js_undefined(), value));
  66. }
  67. // https://webidl.spec.whatwg.org/#reject
  68. void reject_promise(JS::Realm& realm, Promise const& promise, JS::Value reason)
  69. {
  70. auto& vm = realm.vm();
  71. // 1. Perform ! Call(p.[[Reject]], undefined, « r »).
  72. MUST(JS::call(vm, *promise.reject(), JS::js_undefined(), reason));
  73. }
  74. // https://webidl.spec.whatwg.org/#dfn-perform-steps-once-promise-is-settled
  75. JS::NonnullGCPtr<JS::Promise> react_to_promise(Promise const& promise, Optional<ReactionSteps> on_fulfilled_callback, Optional<ReactionSteps> on_rejected_callback)
  76. {
  77. auto& realm = promise.promise()->shape().realm();
  78. auto& vm = realm.vm();
  79. // 1. Let onFulfilledSteps be the following steps given argument V:
  80. auto on_fulfilled_steps = [on_fulfilled_callback = move(on_fulfilled_callback)](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
  81. // 1. Let value be the result of converting V to an IDL value of type T.
  82. auto value = vm.argument(0);
  83. // 2. If there is a set of steps to be run if the promise was fulfilled, then let result be the result of performing them, given value if T is not undefined. Otherwise, let result be value.
  84. auto result = on_fulfilled_callback.has_value()
  85. ? TRY(Bindings::throw_dom_exception_if_needed(vm, [&] { return (*on_fulfilled_callback)(value); }))
  86. : value;
  87. // 3. Return result, converted to an ECMAScript value.
  88. return result;
  89. };
  90. // 2. Let onFulfilled be CreateBuiltinFunction(onFulfilledSteps, « »):
  91. auto on_fulfilled = JS::NativeFunction::create(realm, move(on_fulfilled_steps), 1, "");
  92. // 3. Let onRejectedSteps be the following steps given argument R:
  93. auto on_rejected_steps = [&realm, on_rejected_callback = move(on_rejected_callback)](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
  94. // 1. Let reason be the result of converting R to an IDL value of type any.
  95. auto reason = vm.argument(0);
  96. // 2. If there is a set of steps to be run if the promise was rejected, then let result be the result of performing them, given reason. Otherwise, let result be a promise rejected with reason.
  97. auto result = on_rejected_callback.has_value()
  98. ? TRY(Bindings::throw_dom_exception_if_needed(vm, [&] { return (*on_rejected_callback)(reason); }))
  99. : WebIDL::create_rejected_promise(realm, reason)->promise();
  100. // 3. Return result, converted to an ECMAScript value.
  101. return result;
  102. };
  103. // 4. Let onRejected be CreateBuiltinFunction(onRejectedSteps, « »):
  104. auto on_rejected = JS::NativeFunction::create(realm, move(on_rejected_steps), 1, "");
  105. // 5. Let constructor be promise.[[Promise]].[[Realm]].[[Intrinsics]].[[%Promise%]].
  106. auto constructor = realm.intrinsics().promise_constructor();
  107. // 6. Let newCapability be ? NewPromiseCapability(constructor).
  108. // NOTE: When called with %Promise%, NewPromiseCapability can't throw.
  109. auto new_capability = MUST(JS::new_promise_capability(vm, constructor));
  110. // 7. Return PerformPromiseThen(promise.[[Promise]], onFulfilled, onRejected, newCapability).
  111. auto promise_object = verify_cast<JS::Promise>(promise.promise().ptr());
  112. auto value = promise_object->perform_then(on_fulfilled, on_rejected, new_capability);
  113. return verify_cast<JS::Promise>(value.as_object());
  114. }
  115. // https://webidl.spec.whatwg.org/#upon-fulfillment
  116. JS::NonnullGCPtr<JS::Promise> upon_fulfillment(Promise const& promise, ReactionSteps steps)
  117. {
  118. // 1. Return the result of reacting to promise:
  119. return react_to_promise(promise,
  120. // - If promise was fulfilled with value v, then:
  121. [steps = move(steps)](auto value) {
  122. // 1. Perform steps with v.
  123. // NOTE: The `return` is not immediately obvious, but `steps` may be something like
  124. // "Return the result of ...", which we also need to do _here_.
  125. return steps(value);
  126. },
  127. {});
  128. }
  129. // https://webidl.spec.whatwg.org/#upon-rejection
  130. JS::NonnullGCPtr<JS::Promise> upon_rejection(Promise const& promise, ReactionSteps steps)
  131. {
  132. // 1. Return the result of reacting to promise:
  133. return react_to_promise(promise, {},
  134. // - If promise was rejected with reason r, then:
  135. [steps = move(steps)](auto reason) {
  136. // 1. Perform steps with r.
  137. // NOTE: The `return` is not immediately obvious, but `steps` may be something like
  138. // "Return the result of ...", which we also need to do _here_.
  139. return steps(reason);
  140. });
  141. }
  142. // https://webidl.spec.whatwg.org/#mark-a-promise-as-handled
  143. void mark_promise_as_handled(Promise const& promise)
  144. {
  145. // To mark as handled a Promise<T> promise, set promise.[[Promise]].[[PromiseIsHandled]] to true.
  146. auto promise_object = verify_cast<JS::Promise>(promise.promise().ptr());
  147. promise_object->set_is_handled();
  148. }
  149. struct WaitForAllResults : JS::Cell {
  150. JS_CELL(WaitForAllResults, JS::Cell);
  151. WaitForAllResults(JS::NonnullGCPtr<JS::HeapFunction<void(Vector<JS::Value> const&)>> s, size_t t)
  152. : success_steps(s)
  153. , total(t)
  154. {
  155. // 8. Let result be a list containing total null values.
  156. result.ensure_capacity(total);
  157. for (size_t i = 0; i < total; ++i)
  158. result.unchecked_append(JS::js_null());
  159. }
  160. virtual void visit_edges(JS::Cell::Visitor& visitor) override
  161. {
  162. Base::visit_edges(visitor);
  163. visitor.visit(success_steps);
  164. for (auto& value : result) {
  165. visitor.visit(value);
  166. }
  167. }
  168. JS::NonnullGCPtr<JS::HeapFunction<void(Vector<JS::Value> const&)>> success_steps;
  169. Vector<JS::Value> result;
  170. size_t total = 0;
  171. size_t fulfilled_count = 0;
  172. };
  173. // https://webidl.spec.whatwg.org/#wait-for-all
  174. void wait_for_all(JS::Realm& realm, Vector<JS::NonnullGCPtr<Promise>> const& promises, Function<void(Vector<JS::Value> const&)> success_steps, Function<void(JS::Value)> failure_steps)
  175. {
  176. // FIXME: Fix spec typo, fullfilled --> fulfilled
  177. // 1. Let fullfilledCount be 0.
  178. // Handled later in WaitForAllResults
  179. // 2. Let rejected be false.
  180. auto rejected = false;
  181. // 3. Let rejectionHandlerSteps be the following steps given arg:
  182. auto rejection_handler_steps = [rejected, failure_steps = JS::create_heap_function(realm.heap(), move(failure_steps))](JS::VM& vm) mutable -> JS::ThrowCompletionOr<JS::Value> {
  183. // 1. If rejected is true, abort these steps.
  184. if (rejected)
  185. return JS::js_undefined();
  186. // 2. Set rejected to true.
  187. rejected = true;
  188. // 3. Perform failureSteps given arg.
  189. failure_steps->function()(vm.argument(0));
  190. return JS::js_undefined();
  191. };
  192. // 4. Let rejectionHandler be CreateBuiltinFunction(rejectionHandlerSteps, « »):
  193. auto rejection_handler = JS::NativeFunction::create(realm, move(rejection_handler_steps), 1, "");
  194. // 5. Let total be promises’s size.
  195. auto total = promises.size();
  196. // 6. If total is 0, then:
  197. if (total == 0) {
  198. // 1. Queue a microtask to perform successSteps given « ».
  199. HTML::queue_a_microtask(nullptr, [success_steps = JS::create_heap_function(realm.heap(), move(success_steps))] {
  200. success_steps->function()({});
  201. });
  202. // 2. Return.
  203. return;
  204. }
  205. // 7. Let index be 0.
  206. auto index = 0;
  207. // 8. Let result be a list containing total null values.
  208. // Handled in WaitForAllResults
  209. auto results = realm.heap().allocate<WaitForAllResults>(realm, JS::create_heap_function(realm.heap(), move(success_steps)), total);
  210. // 9. For each promise of promises:
  211. for (auto const& promise : promises) {
  212. // 1. Let promiseIndex be index.
  213. auto promise_index = index;
  214. // FIXME: This should be fulfillmentHandlerSteps
  215. // 2. Let fulfillmentHandler be the following steps given arg:
  216. auto fulfillment_handler_steps = [results, promise_index](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
  217. auto arg = vm.argument(0);
  218. // 1. Set result[promiseIndex] to arg.
  219. results->result[promise_index] = arg;
  220. // 2. Set fullfilledCount to fullfilledCount + 1.
  221. ++results->fulfilled_count;
  222. // 3. If fullfilledCount equals total, then perform successSteps given result.
  223. if (results->fulfilled_count == results->total)
  224. results->success_steps->function()(results->result);
  225. return JS::js_undefined();
  226. };
  227. // 3. Let fulfillmentHandler be CreateBuiltinFunction(fulfillmentHandler, « »):
  228. auto fulfillment_handler = JS::NativeFunction::create(realm, move(fulfillment_handler_steps), 1, "");
  229. // 4. Perform PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler).
  230. static_cast<JS::Promise&>(*promise->promise()).perform_then(fulfillment_handler, rejection_handler, nullptr);
  231. // 5. Set index to index + 1.
  232. ++index;
  233. }
  234. }
  235. }