Skip to main content

quickjs_oxide/engine/api/core/
promise.rs

1//! Promises created and settled from Rust.
2
3use super::ops::{Js, JsResult};
4use super::value::{CallableRef, ObjectRef, Value};
5
6/// A promise and its resolving functions ([`Js::new_promise`]). A host
7/// function returns `promise` at once and keeps the capability; when the
8/// embedder's event arrives it settles the promise from the top level and
9/// drains the job queue.
10#[derive(Clone, Debug, PartialEq)]
11pub struct PromiseCapability {
12    pub promise: ObjectRef,
13    pub resolve: CallableRef,
14    pub reject: CallableRef,
15}
16
17impl PromiseCapability {
18    /// Resolves the promise with `value` (a thenable is followed, as the
19    /// specification's resolve function does). Settling it twice does
20    /// nothing.
21    pub fn resolve(&self, js: &mut impl Js, value: Value) -> JsResult<()> {
22        js.call(&self.resolve, Value::Undefined, &[value]).map(drop)
23    }
24
25    /// Rejects the promise with `reason`.
26    pub fn reject(&self, js: &mut impl Js, reason: Value) -> JsResult<()> {
27        js.call(&self.reject, Value::Undefined, &[reason]).map(drop)
28    }
29}