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;
37use script_bindings::settings_stack::run_a_script;
38
39use crate::DomTypeHolder;
40use crate::dom::bindings::conversions::root_from_object;
41use crate::dom::bindings::error::{Error, ErrorToJsval};
42use crate::dom::bindings::reflector::{DomGlobal, DomObject, MutDomObject, Reflector};
43use crate::dom::bindings::root::{AsHandleValue, DomRoot};
44use crate::dom::globalscope::GlobalScope;
45use crate::dom::promisenativehandler::{Callback, PromiseNativeHandler};
46use crate::microtask::{Microtask, MicrotaskRunnable};
47use crate::realms::{AlreadyInRealm, InRealm, enter_auto_realm, enter_realm};
48use crate::script_runtime::{CanGc, JSContext as SafeJSContext};
49use crate::script_thread::ScriptThread;
50
51#[dom_struct]
52#[cfg_attr(crown, crown::unrooted_must_root_lint::allow_unrooted_in_rc)]
53pub(crate) struct Promise {
54    reflector: Reflector,
55    /// Since Promise values are natively reference counted without the knowledge of
56    /// the SpiderMonkey GC, an explicit root for the reflector is stored while any
57    /// native instance exists. This ensures that the reflector will never be GCed
58    /// while native code could still interact with its native representation.
59    #[ignore_malloc_size_of = "SM handles JS values"]
60    permanent_js_root: Heap<JSVal>,
61}
62
63/// Private helper to enable adding new methods to `Rc<Promise>`.
64trait PromiseHelper {
65    fn initialize(&self, cx: SafeJSContext);
66}
67
68impl PromiseHelper for Rc<Promise> {
69    #[expect(unsafe_code)]
70    fn initialize(&self, cx: SafeJSContext) {
71        let obj = self.reflector().get_jsobject();
72        self.permanent_js_root.set(ObjectValue(*obj));
73        unsafe {
74            assert!(AddRawValueRoot(
75                *cx,
76                self.permanent_js_root.get_unsafe(),
77                c"Promise::root".as_ptr(),
78            ));
79        }
80    }
81}
82
83// Promise objects are stored inside Rc values, so Drop is run when the last Rc is dropped,
84// rather than when SpiderMonkey runs a GC. This makes it safe to interact with the JS engine unlike
85// Drop implementations for other DOM types.
86impl Drop for Promise {
87    #[expect(unsafe_code)]
88    fn drop(&mut self) {
89        unsafe {
90            let object = self.permanent_js_root.get().to_object();
91            assert!(!object.is_null());
92            if let Some(cx) = Runtime::get() {
93                RemoveRawValueRoot(cx.as_ptr(), self.permanent_js_root.get_unsafe());
94            }
95        }
96    }
97}
98
99impl Promise {
100    pub(crate) fn new(global: &GlobalScope, can_gc: CanGc) -> Rc<Promise> {
101        let realm = enter_realm(global);
102        let comp = InRealm::Entered(&realm);
103        Promise::new_in_current_realm(comp, can_gc)
104    }
105
106    pub(crate) fn new_in_current_realm(_comp: InRealm, can_gc: CanGc) -> Rc<Promise> {
107        let cx = GlobalScope::get_cx();
108        rooted!(in(*cx) let mut obj = ptr::null_mut::<JSObject>());
109        Promise::create_js_promise(cx, obj.handle_mut(), can_gc);
110        Promise::new_with_js_promise(obj.handle(), cx)
111    }
112
113    pub(crate) fn new2(cx: &mut js::context::JSContext, global: &GlobalScope) -> Rc<Promise> {
114        let mut realm = AutoRealm::new(
115            cx,
116            std::ptr::NonNull::new(global.reflector().get_jsobject().get()).unwrap(),
117        );
118        let mut current_realm = realm.current_realm();
119        Promise::new_in_realm(&mut current_realm)
120    }
121
122    pub(crate) fn new_in_realm(current_realm: &mut CurrentRealm) -> Rc<Promise> {
123        let cx = current_realm.deref_mut();
124        rooted!(&in(cx) let mut obj = ptr::null_mut::<JSObject>());
125        Promise::create_js_promise(cx.into(), obj.handle_mut(), CanGc::from_cx(cx));
126        Promise::new_with_js_promise(obj.handle(), cx.into())
127    }
128
129    pub(crate) fn duplicate(&self) -> Rc<Promise> {
130        let cx = GlobalScope::get_cx();
131        Promise::new_with_js_promise(self.reflector().get_jsobject(), cx)
132    }
133
134    #[expect(unsafe_code)]
135    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
136    pub(crate) fn new_with_js_promise(obj: HandleObject, cx: SafeJSContext) -> Rc<Promise> {
137        unsafe {
138            assert!(IsPromiseObject(obj));
139            let promise = Promise {
140                reflector: Reflector::new(),
141                permanent_js_root: Heap::default(),
142            };
143            let promise = Rc::new(promise);
144            promise.init_reflector_without_associated_memory(obj.get());
145            promise.initialize(cx);
146            promise
147        }
148    }
149
150    #[expect(unsafe_code)]
151    // The apparently-unused CanGc parameter reflects the fact that the JS API calls
152    // like JS_NewFunction can trigger a GC.
153    fn create_js_promise(cx: SafeJSContext, mut obj: MutableHandleObject, _can_gc: CanGc) {
154        unsafe {
155            let do_nothing_func = JS_NewFunction(
156                *cx,
157                Some(do_nothing_promise_executor),
158                /* nargs = */ 2,
159                /* flags = */ 0,
160                ptr::null(),
161            );
162            assert!(!do_nothing_func.is_null());
163            rooted!(in(*cx) let do_nothing_obj = JS_GetFunctionObject(do_nothing_func));
164            assert!(!do_nothing_obj.is_null());
165            obj.set(NewPromiseObject(*cx, do_nothing_obj.handle()));
166            assert!(!obj.is_null());
167            let is_user_interacting = if ScriptThread::is_user_interacting() {
168                PromiseUserInputEventHandlingState::HadUserInteractionAtCreation
169            } else {
170                PromiseUserInputEventHandlingState::DidntHaveUserInteractionAtCreation
171            };
172            SetPromiseUserInputEventHandlingState(obj.handle(), is_user_interacting);
173        }
174    }
175
176    #[expect(unsafe_code)]
177    pub(crate) fn new_resolved(
178        global: &GlobalScope,
179        cx: SafeJSContext,
180        value: impl SafeToJSValConvertible,
181        can_gc: CanGc,
182    ) -> Rc<Promise> {
183        let _ac = JSAutoRealm::new(*cx, global.reflector().get_jsobject().get());
184        rooted!(in(*cx) let mut rval = UndefinedValue());
185        value.safe_to_jsval(cx, rval.handle_mut(), can_gc);
186        unsafe {
187            rooted!(in(*cx) let p = CallOriginalPromiseResolve(*cx, rval.handle()));
188            assert!(!p.handle().is_null());
189            Promise::new_with_js_promise(p.handle(), cx)
190        }
191    }
192
193    #[expect(unsafe_code)]
194    pub(crate) fn new_rejected(
195        global: &GlobalScope,
196        cx: SafeJSContext,
197        value: impl SafeToJSValConvertible,
198        can_gc: CanGc,
199    ) -> Rc<Promise> {
200        let _ac = JSAutoRealm::new(*cx, global.reflector().get_jsobject().get());
201        rooted!(in(*cx) let mut rval = UndefinedValue());
202        value.safe_to_jsval(cx, rval.handle_mut(), can_gc);
203        unsafe {
204            rooted!(in(*cx) let p = CallOriginalPromiseReject(*cx, rval.handle()));
205            assert!(!p.handle().is_null());
206            Promise::new_with_js_promise(p.handle(), cx)
207        }
208    }
209
210    pub(crate) fn resolve_native<T>(&self, val: &T, can_gc: CanGc)
211    where
212        T: SafeToJSValConvertible,
213    {
214        let cx = GlobalScope::get_cx();
215        let _ac = enter_realm(self);
216        rooted!(in(*cx) let mut v = UndefinedValue());
217        val.safe_to_jsval(cx, v.handle_mut(), can_gc);
218        self.resolve(cx, v.handle(), can_gc);
219    }
220
221    #[expect(unsafe_code)]
222    pub(crate) fn resolve(&self, cx: SafeJSContext, value: HandleValue, _can_gc: CanGc) {
223        unsafe {
224            if !ResolvePromise(*cx, self.promise_obj(), value) {
225                JS_ClearPendingException(*cx);
226            }
227        }
228    }
229
230    pub(crate) fn reject_native<T>(&self, val: &T, can_gc: CanGc)
231    where
232        T: SafeToJSValConvertible,
233    {
234        let cx = GlobalScope::get_cx();
235        let _ac = enter_realm(self);
236        rooted!(in(*cx) let mut v = UndefinedValue());
237        val.safe_to_jsval(cx, v.handle_mut(), can_gc);
238        self.reject(cx, v.handle(), can_gc);
239    }
240
241    pub(crate) fn reject_error(&self, error: Error, can_gc: CanGc) {
242        let cx = GlobalScope::get_cx();
243        let _ac = enter_realm(self);
244        rooted!(in(*cx) let mut v = UndefinedValue());
245        error.to_jsval(cx, &self.global(), v.handle_mut(), can_gc);
246        self.reject(cx, v.handle(), can_gc);
247    }
248
249    #[expect(unsafe_code)]
250    pub(crate) fn reject(&self, cx: SafeJSContext, value: HandleValue, _can_gc: CanGc) {
251        unsafe {
252            if !RejectPromise(*cx, self.promise_obj(), value) {
253                JS_ClearPendingException(*cx);
254            }
255        }
256    }
257
258    #[expect(unsafe_code)]
259    pub(crate) fn is_fulfilled(&self) -> bool {
260        let state = unsafe { GetPromiseState(self.promise_obj()) };
261        matches!(state, PromiseState::Rejected | PromiseState::Fulfilled)
262    }
263
264    #[expect(unsafe_code)]
265    pub(crate) fn is_rejected(&self) -> bool {
266        let state = unsafe { GetPromiseState(self.promise_obj()) };
267        matches!(state, PromiseState::Rejected)
268    }
269
270    #[expect(unsafe_code)]
271    pub(crate) fn is_pending(&self) -> bool {
272        let state = unsafe { GetPromiseState(self.promise_obj()) };
273        matches!(state, PromiseState::Pending)
274    }
275
276    #[expect(unsafe_code)]
277    pub(crate) fn promise_obj(&self) -> HandleObject<'_> {
278        let obj = self.reflector().get_jsobject();
279        unsafe {
280            assert!(IsPromiseObject(obj));
281        }
282        obj
283    }
284
285    #[expect(unsafe_code)]
286    pub(crate) fn append_native_handler(
287        &self,
288        handler: &PromiseNativeHandler,
289        realm: InRealm,
290        can_gc: CanGc,
291    ) {
292        run_a_script::<DomTypeHolder, _>(&handler.global_(realm), || {
293            let cx = GlobalScope::get_cx();
294            rooted!(in(*cx) let resolve_func =
295                create_native_handler_function(*cx,
296                                               handler.reflector().get_jsobject(),
297                                               NativeHandlerTask::Resolve,
298                                               can_gc));
299
300            rooted!(in(*cx) let reject_func =
301                create_native_handler_function(*cx,
302                                               handler.reflector().get_jsobject(),
303                                               NativeHandlerTask::Reject,
304                                               can_gc));
305
306            unsafe {
307                let ok = AddPromiseReactions(
308                    *cx,
309                    self.promise_obj(),
310                    resolve_func.handle(),
311                    reject_func.handle(),
312                );
313                assert!(ok);
314            }
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(c"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::deprecated_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, _cx: &mut JSContext) {
530        (self.success_steps)(vec![]);
531    }
532
533    fn enter_realm<'cx>(&self, cx: &'cx mut JSContext) -> AutoRealm<'cx> {
534        enter_auto_realm(cx, &*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}