script/dom/
promise.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! Native representation of JS Promise values.
6//!
7//! This implementation differs from the traditional Rust DOM object, because the reflector
8//! is provided by SpiderMonkey and has no knowledge of an associated native representation
9//! (ie. dom::Promise). This means that native instances use native reference counting (Rc)
10//! to ensure that no memory is leaked, which means that there can be multiple instances of
11//! native Promise values that refer to the same JS value yet are distinct native objects
12//! (ie. address equality for the native objects is meaningless).
13
14use std::cell::{Cell, RefCell};
15use std::ops::DerefMut;
16use std::ptr;
17use std::rc::Rc;
18
19use dom_struct::dom_struct;
20use js::context::JSContext;
21use js::conversions::{ConversionResult, FromJSValConvertibleRc};
22use js::jsapi::{
23    AddRawValueRoot, CallArgs, GetFunctionNativeReserved, Heap, JS_ClearPendingException,
24    JS_GetFunctionObject, JS_NewFunction, JSAutoRealm, JSContext as RawJSContext, JSObject,
25    NewFunctionWithReserved, PromiseState, PromiseUserInputEventHandlingState, RemoveRawValueRoot,
26    SetFunctionNativeReserved,
27};
28use js::jsval::{Int32Value, JSVal, NullValue, ObjectValue, UndefinedValue};
29use js::realm::{AutoRealm, CurrentRealm};
30use js::rust::wrappers::{
31    AddPromiseReactions, CallOriginalPromiseReject, CallOriginalPromiseResolve,
32    GetPromiseIsHandled, GetPromiseState, IsPromiseObject, NewPromiseObject, RejectPromise,
33    ResolvePromise, SetAnyPromiseIsHandled, SetPromiseUserInputEventHandlingState,
34};
35use js::rust::{HandleObject, HandleValue, MutableHandleObject, Runtime};
36use script_bindings::conversions::SafeToJSValConvertible;
37
38use crate::dom::bindings::conversions::root_from_object;
39use crate::dom::bindings::error::{Error, ErrorToJsval};
40use crate::dom::bindings::reflector::{DomGlobal, DomObject, MutDomObject, Reflector};
41use crate::dom::bindings::root::{AsHandleValue, DomRoot};
42use crate::dom::bindings::settings_stack::AutoEntryScript;
43use crate::dom::globalscope::GlobalScope;
44use crate::dom::promisenativehandler::{Callback, PromiseNativeHandler};
45use crate::microtask::{Microtask, MicrotaskRunnable};
46use crate::realms::{AlreadyInRealm, InRealm, enter_realm};
47use crate::script_runtime::{CanGc, JSContext as SafeJSContext};
48use crate::script_thread::ScriptThread;
49
50#[dom_struct]
51#[cfg_attr(crown, crown::unrooted_must_root_lint::allow_unrooted_in_rc)]
52pub(crate) struct Promise {
53    reflector: Reflector,
54    /// Since Promise values are natively reference counted without the knowledge of
55    /// the SpiderMonkey GC, an explicit root for the reflector is stored while any
56    /// native instance exists. This ensures that the reflector will never be GCed
57    /// while native code could still interact with its native representation.
58    #[ignore_malloc_size_of = "SM handles JS values"]
59    permanent_js_root: Heap<JSVal>,
60}
61
62/// Private helper to enable adding new methods to `Rc<Promise>`.
63trait PromiseHelper {
64    fn initialize(&self, cx: SafeJSContext);
65}
66
67impl PromiseHelper for Rc<Promise> {
68    #[expect(unsafe_code)]
69    fn initialize(&self, cx: SafeJSContext) {
70        let obj = self.reflector().get_jsobject();
71        self.permanent_js_root.set(ObjectValue(*obj));
72        unsafe {
73            assert!(AddRawValueRoot(
74                *cx,
75                self.permanent_js_root.get_unsafe(),
76                c"Promise::root".as_ptr(),
77            ));
78        }
79    }
80}
81
82// Promise objects are stored inside Rc values, so Drop is run when the last Rc is dropped,
83// rather than when SpiderMonkey runs a GC. This makes it safe to interact with the JS engine unlike
84// Drop implementations for other DOM types.
85impl Drop for Promise {
86    #[expect(unsafe_code)]
87    fn drop(&mut self) {
88        let reflector = script_bindings::reflector::DomObject::reflector(self);
89        reflector.drop_memory(self);
90        unsafe {
91            let object = self.permanent_js_root.get().to_object();
92            assert!(!object.is_null());
93            if let Some(cx) = Runtime::get() {
94                RemoveRawValueRoot(cx.as_ptr(), self.permanent_js_root.get_unsafe());
95            }
96        }
97    }
98}
99
100impl Promise {
101    pub(crate) fn new(global: &GlobalScope, can_gc: CanGc) -> Rc<Promise> {
102        let realm = enter_realm(global);
103        let comp = InRealm::Entered(&realm);
104        Promise::new_in_current_realm(comp, can_gc)
105    }
106
107    pub(crate) fn new_in_current_realm(_comp: InRealm, can_gc: CanGc) -> Rc<Promise> {
108        let cx = GlobalScope::get_cx();
109        rooted!(in(*cx) let mut obj = ptr::null_mut::<JSObject>());
110        Promise::create_js_promise(cx, obj.handle_mut(), can_gc);
111        Promise::new_with_js_promise(obj.handle(), cx)
112    }
113
114    pub(crate) fn new2(cx: &mut js::context::JSContext, global: &GlobalScope) -> Rc<Promise> {
115        let mut realm = AutoRealm::new(
116            cx,
117            std::ptr::NonNull::new(global.reflector().get_jsobject().get()).unwrap(),
118        );
119        let mut current_realm = realm.current_realm();
120        Promise::new_in_realm(&mut current_realm)
121    }
122
123    pub(crate) fn new_in_realm(current_realm: &mut CurrentRealm) -> Rc<Promise> {
124        let cx = current_realm.deref_mut();
125        rooted!(&in(cx) let mut obj = ptr::null_mut::<JSObject>());
126        Promise::create_js_promise(cx.into(), obj.handle_mut(), CanGc::from_cx(cx));
127        Promise::new_with_js_promise(obj.handle(), cx.into())
128    }
129
130    pub(crate) fn duplicate(&self) -> Rc<Promise> {
131        let cx = GlobalScope::get_cx();
132        Promise::new_with_js_promise(self.reflector().get_jsobject(), cx)
133    }
134
135    #[expect(unsafe_code)]
136    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
137    pub(crate) fn new_with_js_promise(obj: HandleObject, cx: SafeJSContext) -> Rc<Promise> {
138        unsafe {
139            assert!(IsPromiseObject(obj));
140            let promise = Promise {
141                reflector: Reflector::new(),
142                permanent_js_root: Heap::default(),
143            };
144            let promise = Rc::new(promise);
145            promise.init_reflector::<Promise>(obj.get());
146            promise.initialize(cx);
147            promise
148        }
149    }
150
151    #[expect(unsafe_code)]
152    // The apparently-unused CanGc parameter reflects the fact that the JS API calls
153    // like JS_NewFunction can trigger a GC.
154    fn create_js_promise(cx: SafeJSContext, mut obj: MutableHandleObject, _can_gc: CanGc) {
155        unsafe {
156            let do_nothing_func = JS_NewFunction(
157                *cx,
158                Some(do_nothing_promise_executor),
159                /* nargs = */ 2,
160                /* flags = */ 0,
161                ptr::null(),
162            );
163            assert!(!do_nothing_func.is_null());
164            rooted!(in(*cx) let do_nothing_obj = JS_GetFunctionObject(do_nothing_func));
165            assert!(!do_nothing_obj.is_null());
166            obj.set(NewPromiseObject(*cx, do_nothing_obj.handle()));
167            assert!(!obj.is_null());
168            let is_user_interacting = if ScriptThread::is_user_interacting() {
169                PromiseUserInputEventHandlingState::HadUserInteractionAtCreation
170            } else {
171                PromiseUserInputEventHandlingState::DidntHaveUserInteractionAtCreation
172            };
173            SetPromiseUserInputEventHandlingState(obj.handle(), is_user_interacting);
174        }
175    }
176
177    #[expect(unsafe_code)]
178    pub(crate) fn new_resolved(
179        global: &GlobalScope,
180        cx: SafeJSContext,
181        value: impl SafeToJSValConvertible,
182        can_gc: CanGc,
183    ) -> Rc<Promise> {
184        let _ac = JSAutoRealm::new(*cx, global.reflector().get_jsobject().get());
185        rooted!(in(*cx) let mut rval = UndefinedValue());
186        value.safe_to_jsval(cx, rval.handle_mut(), can_gc);
187        unsafe {
188            rooted!(in(*cx) let p = CallOriginalPromiseResolve(*cx, rval.handle()));
189            assert!(!p.handle().is_null());
190            Promise::new_with_js_promise(p.handle(), cx)
191        }
192    }
193
194    #[expect(unsafe_code)]
195    pub(crate) fn new_rejected(
196        global: &GlobalScope,
197        cx: SafeJSContext,
198        value: impl SafeToJSValConvertible,
199        can_gc: CanGc,
200    ) -> Rc<Promise> {
201        let _ac = JSAutoRealm::new(*cx, global.reflector().get_jsobject().get());
202        rooted!(in(*cx) let mut rval = UndefinedValue());
203        value.safe_to_jsval(cx, rval.handle_mut(), can_gc);
204        unsafe {
205            rooted!(in(*cx) let p = CallOriginalPromiseReject(*cx, rval.handle()));
206            assert!(!p.handle().is_null());
207            Promise::new_with_js_promise(p.handle(), cx)
208        }
209    }
210
211    pub(crate) fn resolve_native<T>(&self, val: &T, can_gc: CanGc)
212    where
213        T: SafeToJSValConvertible,
214    {
215        let cx = GlobalScope::get_cx();
216        let _ac = enter_realm(self);
217        rooted!(in(*cx) let mut v = UndefinedValue());
218        val.safe_to_jsval(cx, v.handle_mut(), can_gc);
219        self.resolve(cx, v.handle(), can_gc);
220    }
221
222    #[expect(unsafe_code)]
223    pub(crate) fn resolve(&self, cx: SafeJSContext, value: HandleValue, _can_gc: CanGc) {
224        unsafe {
225            if !ResolvePromise(*cx, self.promise_obj(), value) {
226                JS_ClearPendingException(*cx);
227            }
228        }
229    }
230
231    pub(crate) fn reject_native<T>(&self, val: &T, can_gc: CanGc)
232    where
233        T: SafeToJSValConvertible,
234    {
235        let cx = GlobalScope::get_cx();
236        let _ac = enter_realm(self);
237        rooted!(in(*cx) let mut v = UndefinedValue());
238        val.safe_to_jsval(cx, v.handle_mut(), can_gc);
239        self.reject(cx, v.handle(), can_gc);
240    }
241
242    pub(crate) fn reject_error(&self, error: Error, can_gc: CanGc) {
243        let cx = GlobalScope::get_cx();
244        let _ac = enter_realm(self);
245        rooted!(in(*cx) let mut v = UndefinedValue());
246        error.to_jsval(cx, &self.global(), v.handle_mut(), can_gc);
247        self.reject(cx, v.handle(), can_gc);
248    }
249
250    #[expect(unsafe_code)]
251    pub(crate) fn reject(&self, cx: SafeJSContext, value: HandleValue, _can_gc: CanGc) {
252        unsafe {
253            if !RejectPromise(*cx, self.promise_obj(), value) {
254                JS_ClearPendingException(*cx);
255            }
256        }
257    }
258
259    #[expect(unsafe_code)]
260    pub(crate) fn is_fulfilled(&self) -> bool {
261        let state = unsafe { GetPromiseState(self.promise_obj()) };
262        matches!(state, PromiseState::Rejected | PromiseState::Fulfilled)
263    }
264
265    #[expect(unsafe_code)]
266    pub(crate) fn is_rejected(&self) -> bool {
267        let state = unsafe { GetPromiseState(self.promise_obj()) };
268        matches!(state, PromiseState::Rejected)
269    }
270
271    #[expect(unsafe_code)]
272    pub(crate) fn is_pending(&self) -> bool {
273        let state = unsafe { GetPromiseState(self.promise_obj()) };
274        matches!(state, PromiseState::Pending)
275    }
276
277    #[expect(unsafe_code)]
278    pub(crate) fn promise_obj(&self) -> HandleObject<'_> {
279        let obj = self.reflector().get_jsobject();
280        unsafe {
281            assert!(IsPromiseObject(obj));
282        }
283        obj
284    }
285
286    #[expect(unsafe_code)]
287    pub(crate) fn append_native_handler(
288        &self,
289        handler: &PromiseNativeHandler,
290        realm: InRealm,
291        can_gc: CanGc,
292    ) {
293        let _ais = AutoEntryScript::new(&handler.global_(realm));
294        let cx = GlobalScope::get_cx();
295        rooted!(in(*cx) let resolve_func =
296                create_native_handler_function(*cx,
297                                               handler.reflector().get_jsobject(),
298                                               NativeHandlerTask::Resolve,
299                                               can_gc));
300
301        rooted!(in(*cx) let reject_func =
302                create_native_handler_function(*cx,
303                                               handler.reflector().get_jsobject(),
304                                               NativeHandlerTask::Reject,
305                                               can_gc));
306
307        unsafe {
308            let ok = AddPromiseReactions(
309                *cx,
310                self.promise_obj(),
311                resolve_func.handle(),
312                reject_func.handle(),
313            );
314            assert!(ok);
315        }
316    }
317
318    #[expect(unsafe_code)]
319    pub(crate) fn get_promise_is_handled(&self) -> bool {
320        unsafe { GetPromiseIsHandled(self.reflector().get_jsobject()) }
321    }
322
323    #[expect(unsafe_code)]
324    pub(crate) fn set_promise_is_handled(&self) -> bool {
325        let cx = GlobalScope::get_cx();
326        unsafe { SetAnyPromiseIsHandled(*cx, self.reflector().get_jsobject()) }
327    }
328}
329
330#[expect(unsafe_code)]
331unsafe extern "C" fn do_nothing_promise_executor(
332    _cx: *mut RawJSContext,
333    argc: u32,
334    vp: *mut JSVal,
335) -> bool {
336    let args = unsafe { CallArgs::from_vp(vp, argc) };
337    args.rval().set(UndefinedValue());
338    true
339}
340
341const SLOT_NATIVEHANDLER: usize = 0;
342const SLOT_NATIVEHANDLER_TASK: usize = 1;
343
344#[derive(PartialEq)]
345enum NativeHandlerTask {
346    Resolve = 0,
347    Reject = 1,
348}
349
350#[expect(unsafe_code)]
351unsafe extern "C" fn native_handler_callback(
352    cx: *mut RawJSContext,
353    argc: u32,
354    vp: *mut JSVal,
355) -> bool {
356    // Safety: it is safe to construct a JSContext from engine hook.
357    let mut cx = unsafe { JSContext::from_ptr(ptr::NonNull::new(cx).unwrap()) };
358    let mut cx = CurrentRealm::assert(&mut cx);
359    let cx = &mut cx;
360
361    let args = unsafe { CallArgs::from_vp(vp, argc) };
362    let native_handler_value =
363        unsafe { *GetFunctionNativeReserved(args.callee(), SLOT_NATIVEHANDLER) };
364    rooted!(&in(cx) let native_handler_value = native_handler_value);
365    assert!(native_handler_value.get().is_object());
366
367    let handler = unsafe {
368        root_from_object::<PromiseNativeHandler>(native_handler_value.to_object(), cx.raw_cx())
369    }
370    .expect("unexpected value for native handler in promise native handler callback");
371
372    let native_handler_task_value =
373        unsafe { *GetFunctionNativeReserved(args.callee(), SLOT_NATIVEHANDLER_TASK) };
374    rooted!(&in(cx) let native_handler_task_value = native_handler_task_value);
375    match native_handler_task_value.to_int32() {
376        native_handler_task_value
377            if native_handler_task_value == NativeHandlerTask::Resolve as i32 =>
378        {
379            handler.resolved_callback(cx, unsafe { HandleValue::from_raw(args.get(0)) })
380        },
381        native_handler_task_value
382            if native_handler_task_value == NativeHandlerTask::Reject as i32 =>
383        {
384            handler.rejected_callback(cx, unsafe { HandleValue::from_raw(args.get(0)) })
385        },
386        _ => panic!("unexpected native handler task value"),
387    };
388
389    true
390}
391
392#[expect(unsafe_code)]
393// The apparently-unused CanGc argument reflects the fact that the JS API calls
394// like NewFunctionWithReserved can trigger a GC.
395fn create_native_handler_function(
396    cx: *mut RawJSContext,
397    holder: HandleObject,
398    task: NativeHandlerTask,
399    _can_gc: CanGc,
400) -> *mut JSObject {
401    unsafe {
402        let func = NewFunctionWithReserved(cx, Some(native_handler_callback), 1, 0, ptr::null());
403        assert!(!func.is_null());
404
405        rooted!(in(cx) let obj = JS_GetFunctionObject(func));
406        assert!(!obj.is_null());
407        SetFunctionNativeReserved(obj.get(), SLOT_NATIVEHANDLER, &ObjectValue(*holder));
408        SetFunctionNativeReserved(obj.get(), SLOT_NATIVEHANDLER_TASK, &Int32Value(task as i32));
409        obj.get()
410    }
411}
412
413impl FromJSValConvertibleRc for Promise {
414    #[expect(unsafe_code)]
415    unsafe fn from_jsval(
416        cx: *mut RawJSContext,
417        value: HandleValue,
418    ) -> Result<ConversionResult<Rc<Promise>>, ()> {
419        if value.get().is_null() {
420            return Ok(ConversionResult::Failure("null not allowed".into()));
421        }
422
423        let cx = unsafe { SafeJSContext::from_ptr(cx) };
424        let in_realm_proof = AlreadyInRealm::assert_for_cx(cx);
425        let global_scope =
426            unsafe { GlobalScope::from_context(*cx, InRealm::Already(&in_realm_proof)) };
427
428        let promise = Promise::new_resolved(&global_scope, cx, value, CanGc::note());
429        Ok(ConversionResult::Success(promise))
430    }
431}
432
433/// The success steps of <https://webidl.spec.whatwg.org/#wait-for-all>
434type WaitForAllSuccessSteps = Rc<dyn Fn(Vec<HandleValue>)>;
435
436/// The failure steps of <https://webidl.spec.whatwg.org/#wait-for-all>
437type WaitForAllFailureSteps = Rc<dyn Fn(HandleValue)>;
438
439/// The fulfillment handler for the list of promises in
440/// <https://webidl.spec.whatwg.org/#wait-for-all>.
441#[derive(JSTraceable, MallocSizeOf)]
442#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
443struct WaitForAllFulfillmentHandler {
444    /// The steps to call when all promises are resolved.
445    #[ignore_malloc_size_of = "callbacks are hard"]
446    #[no_trace]
447    success_steps: WaitForAllSuccessSteps,
448
449    /// The results of the promises.
450    #[ignore_malloc_size_of = "mozjs"]
451    #[expect(clippy::vec_box)]
452    result: Rc<RefCell<Vec<Box<Heap<JSVal>>>>>,
453
454    /// The index identifying which promise this handler is attached to.
455    promise_index: usize,
456
457    /// A count of fulfilled promises.
458    #[conditional_malloc_size_of]
459    fulfilled_count: Rc<RefCell<usize>>,
460}
461
462impl Callback for WaitForAllFulfillmentHandler {
463    fn callback(&self, _cx: &mut CurrentRealm, v: HandleValue) {
464        // Let fulfillmentHandler be the following steps given arg:
465
466        let equals_total = {
467            // Set result[promiseIndex] to arg.
468            let result = self.result.borrow_mut();
469            result[self.promise_index].set(v.get());
470
471            // Set fulfilledCount to fulfilledCount + 1.
472            let mut fulfilled_count = self.fulfilled_count.borrow_mut();
473            *fulfilled_count += 1;
474
475            *fulfilled_count == result.len()
476        };
477
478        // If fulfilledCount equals total, then perform successSteps given result.
479        if equals_total {
480            let result_ref = self.result.borrow();
481            let result_handles: Vec<HandleValue> =
482                result_ref.iter().map(|v| v.as_handle_value()).collect();
483
484            (self.success_steps)(result_handles);
485        }
486    }
487}
488
489/// The rejection handler for the list of promises in
490/// <https://webidl.spec.whatwg.org/#wait-for-all>.
491#[derive(Clone, JSTraceable, MallocSizeOf)]
492struct WaitForAllRejectionHandler {
493    /// The steps to call if any promise rejects.
494    #[ignore_malloc_size_of = "callbacks are hard"]
495    #[no_trace]
496    failure_steps: WaitForAllFailureSteps,
497
498    /// Whether any promises have been rejected already.
499    rejected: Cell<bool>,
500}
501
502impl Callback for WaitForAllRejectionHandler {
503    fn callback(&self, _cx: &mut CurrentRealm, v: HandleValue) {
504        // Let rejectionHandlerSteps be the following steps given arg:
505
506        if self.rejected.replace(true) {
507            // If rejected is true, abort these steps.
508            return;
509        }
510
511        // Set rejected to true.
512        // Done above with `replace`.
513        (self.failure_steps)(v);
514    }
515}
516
517/// The microtask for performing successSteps given « » in
518/// <https://webidl.spec.whatwg.org/#wait-for-all>.
519#[derive(JSTraceable, MallocSizeOf)]
520pub(crate) struct WaitForAllSuccessStepsMicrotask {
521    global: DomRoot<GlobalScope>,
522
523    #[ignore_malloc_size_of = "Closure is hard"]
524    #[no_trace]
525    success_steps: WaitForAllSuccessSteps,
526}
527
528impl MicrotaskRunnable for WaitForAllSuccessStepsMicrotask {
529    fn handler(&self, _can_gc: CanGc) {
530        (self.success_steps)(vec![]);
531    }
532
533    fn enter_realm(&self) -> JSAutoRealm {
534        enter_realm(&*self.global)
535    }
536}
537
538/// <https://webidl.spec.whatwg.org/#wait-for-all>
539#[cfg_attr(crown, expect(crown::unrooted_must_root))]
540pub(crate) fn wait_for_all(
541    cx: SafeJSContext,
542    global: &GlobalScope,
543    promises: Vec<Rc<Promise>>,
544    success_steps: WaitForAllSuccessSteps,
545    failure_steps: WaitForAllFailureSteps,
546    realm: InRealm,
547    can_gc: CanGc,
548) {
549    // Let fulfilledCount be 0.
550    let fulfilled_count: Rc<RefCell<usize>> = Default::default();
551
552    // Let rejected be false.
553    // Note: done below when constructing a rejection handler.
554
555    // Let rejectionHandlerSteps be the following steps given arg:
556    // Note: implemented with the `WaitForAllRejectionHandler`.
557
558    // Let rejectionHandler be CreateBuiltinFunction(rejectionHandlerSteps, « »):
559    // Note: done as part of attaching the `WaitForAllRejectionHandler` as native rejection handler.
560    let rejection_handler = WaitForAllRejectionHandler {
561        failure_steps,
562        rejected: Default::default(),
563    };
564
565    // Let total be promises’s size.
566    // Note: done using the len of result.
567
568    // If total is 0, then:
569    if promises.is_empty() {
570        // Queue a microtask to perform successSteps given « ».
571        global.enqueue_microtask(Microtask::WaitForAllSuccessSteps(
572            WaitForAllSuccessStepsMicrotask {
573                global: DomRoot::from_ref(global),
574                success_steps,
575            },
576        ));
577
578        // Return.
579        return;
580    }
581
582    // Let index be 0.
583    // Note: done with `enumerate` below.
584
585    // Let result be a list containing total null values.
586    let result: Rc<RefCell<Vec<Box<Heap<JSVal>>>>> = Default::default();
587
588    // For each promise of promises:
589    for (promise_index, promise) in promises.into_iter().enumerate() {
590        let result = result.clone();
591
592        {
593            // Note: adding a null value for this promise result.
594            let mut result_list = result.borrow_mut();
595            rooted!(in(*cx) let null_value = NullValue());
596            result_list.push(Heap::boxed(null_value.get()));
597        }
598
599        // Let promiseIndex be index.
600        // Note: done with `enumerate` above.
601
602        // Let fulfillmentHandler be the following steps given arg:
603        // Note: implemented with the `WaitForAllFulFillmentHandler`.
604
605        // Let fulfillmentHandler be CreateBuiltinFunction(fulfillmentHandler, « »):
606        // Note: passed below to avoid the need to root it.
607
608        // Perform PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler).
609        let handler = PromiseNativeHandler::new(
610            global,
611            Some(Box::new(WaitForAllFulfillmentHandler {
612                success_steps: success_steps.clone(),
613                result,
614                promise_index,
615                fulfilled_count: fulfilled_count.clone(),
616            })),
617            Some(Box::new(rejection_handler.clone())),
618            can_gc,
619        );
620        promise.append_native_handler(&handler, realm, can_gc);
621
622        // Set index to index + 1.
623        // Note: done above with `enumerate`.
624    }
625}
626
627/// <https://webidl.spec.whatwg.org/#waiting-for-all-promise>
628pub(crate) fn wait_for_all_promise(
629    cx: SafeJSContext,
630    global: &GlobalScope,
631    promises: Vec<Rc<Promise>>,
632    realm: InRealm,
633    can_gc: CanGc,
634) -> Rc<Promise> {
635    // Let promise be a new promise of type Promise<sequence<T>> in realm.
636    let promise = Promise::new(global, can_gc);
637    let success_promise = promise.clone();
638    let failure_promise = promise.clone();
639
640    // Let successSteps be the following steps, given results:
641    let success_steps = Rc::new(move |results: Vec<HandleValue>| {
642        // Resolve promise with results.
643        success_promise.resolve_native(&results, can_gc);
644    });
645
646    // Let failureSteps be the following steps, given reason:
647    let failure_steps = Rc::new(move |reason: HandleValue| {
648        // Reject promise with reason.
649        failure_promise.reject_native(&reason, can_gc);
650    });
651
652    // Wait for all with promises, given successSteps and failureSteps.
653    wait_for_all(
654        cx,
655        global,
656        promises,
657        success_steps,
658        failure_steps,
659        realm,
660        can_gc,
661    );
662
663    // Return promise.
664    promise
665}