quickjs_rusty/value/
promise.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
use std::ops::Deref;

use libquickjs_ng_sys as q;

use crate::utils::ensure_no_excpetion;
use crate::{Context, ExecutionError, JsFunction, ValueError};

use super::OwnedJsValue;

#[derive(Debug, Clone, PartialEq)]
pub struct OwnedJsPromise {
    value: OwnedJsValue,
}

impl OwnedJsPromise {
    pub fn try_from_value(value: OwnedJsValue) -> Result<Self, ValueError> {
        if !value.is_promise() {
            Err(ValueError::Internal("Expected an promise".into()))
        } else {
            Ok(Self { value })
        }
    }

    pub fn into_value(self) -> OwnedJsValue {
        self.value
    }

    pub fn state(&self) -> PromiseState {
        let state = unsafe { q::JS_PromiseState(self.value.context(), self.value.value) };
        match state {
            q::JSPromiseStateEnum_JS_PROMISE_PENDING => PromiseState::Pending,
            q::JSPromiseStateEnum_JS_PROMISE_FULFILLED => PromiseState::Fulfilled,
            q::JSPromiseStateEnum_JS_PROMISE_REJECTED => PromiseState::Rejected,
            _ => unreachable!(),
        }
    }

    /// Returns the result of the promise if the promise's state is in the FULFILLED or REJECTED state,
    /// otherwise returns Undefined.
    pub fn result(&self) -> OwnedJsValue {
        let result = unsafe { q::JS_PromiseResult(self.value.context(), self.value.value) };
        OwnedJsValue::new(self.value.context(), result)
    }

    pub fn then(&self, on_fulfilled: &OwnedJsValue) -> Result<OwnedJsPromise, ExecutionError> {
        let new_promise = unsafe {
            q::JS_Ext_PromiseThen(self.value.context(), self.value.value, on_fulfilled.value)
        };

        let new_promise = OwnedJsValue::new(self.value.context(), new_promise);

        ensure_no_excpetion(self.value.context())?;

        Ok(OwnedJsPromise::try_from_value(new_promise)?)
    }

    pub fn then2(
        &self,
        on_fulfilled: &OwnedJsValue,
        on_rejected: &OwnedJsValue,
    ) -> Result<OwnedJsPromise, ExecutionError> {
        let new_promise = unsafe {
            q::JS_Ext_PromiseThen2(
                self.value.context(),
                self.value.value,
                on_fulfilled.value,
                on_rejected.value,
            )
        };

        let new_promise = OwnedJsValue::new(self.value.context(), new_promise);

        ensure_no_excpetion(self.value.context())?;

        Ok(OwnedJsPromise::try_from_value(new_promise)?)
    }

    pub fn catch(&self, on_rejected: &OwnedJsValue) -> Result<OwnedJsPromise, ExecutionError> {
        let new_promise = unsafe {
            q::JS_Ext_PromiseCatch(self.value.context(), self.value.value, on_rejected.value)
        };

        let new_promise = OwnedJsValue::new(self.value.context(), new_promise);

        ensure_no_excpetion(self.value.context())?;

        Ok(OwnedJsPromise::try_from_value(new_promise)?)
    }

    pub fn finally(&self, on_finally: &OwnedJsValue) -> Result<OwnedJsPromise, ExecutionError> {
        let new_promise = unsafe {
            q::JS_Ext_PromiseFinally(self.value.context(), self.value.value, on_finally.value)
        };

        let new_promise = OwnedJsValue::new(self.value.context(), new_promise);

        ensure_no_excpetion(self.value.context())?;

        Ok(OwnedJsPromise::try_from_value(new_promise)?)
    }

    pub fn resolve(
        context: &Context,
        value: &OwnedJsValue,
    ) -> Result<OwnedJsPromise, ExecutionError> {
        let promise = unsafe { q::JS_Ext_PromiseResolve(context.context, value.value) };
        let promise = OwnedJsValue::new(context.context, promise);

        ensure_no_excpetion(context.context)?;

        Ok(OwnedJsPromise::try_from_value(promise)?)
    }

    pub fn reject(
        context: &Context,
        value: &OwnedJsValue,
    ) -> Result<OwnedJsPromise, ExecutionError> {
        let promise = unsafe { q::JS_Ext_PromiseReject(context.context, value.value) };
        let promise = OwnedJsValue::new(context.context, promise);

        ensure_no_excpetion(context.context)?;

        Ok(OwnedJsPromise::try_from_value(promise)?)
    }

    pub fn all(
        context: &Context,
        values: impl IntoIterator<Item = OwnedJsPromise>,
    ) -> Result<OwnedJsPromise, ExecutionError> {
        let iterable: OwnedJsValue =
            (context.context, values.into_iter().collect::<Vec<_>>()).into();

        let promise = unsafe { q::JS_Ext_PromiseAll(context.context, iterable.value) };
        let promise = OwnedJsValue::new(context.context, promise);

        ensure_no_excpetion(context.context)?;

        Ok(OwnedJsPromise::try_from_value(promise)?)
    }

    pub fn all_settled(
        context: &Context,
        values: impl IntoIterator<Item = OwnedJsPromise>,
    ) -> Result<OwnedJsPromise, ExecutionError> {
        let iterable: OwnedJsValue =
            (context.context, values.into_iter().collect::<Vec<_>>()).into();

        let promise = unsafe { q::JS_Ext_PromiseAllSettled(context.context, iterable.value) };
        let promise = OwnedJsValue::new(context.context, promise);

        ensure_no_excpetion(context.context)?;

        Ok(OwnedJsPromise::try_from_value(promise)?)
    }

    pub fn race(
        context: &Context,
        values: impl IntoIterator<Item = OwnedJsPromise>,
    ) -> Result<OwnedJsPromise, ExecutionError> {
        let iterable: OwnedJsValue =
            (context.context, values.into_iter().collect::<Vec<_>>()).into();

        let promise = unsafe { q::JS_Ext_PromiseRace(context.context, iterable.value) };
        let promise = OwnedJsValue::new(context.context, promise);

        ensure_no_excpetion(context.context)?;

        Ok(OwnedJsPromise::try_from_value(promise)?)
    }

    pub fn any(
        context: &Context,
        values: impl IntoIterator<Item = OwnedJsPromise>,
    ) -> Result<OwnedJsPromise, ExecutionError> {
        let iterable: OwnedJsValue =
            (context.context, values.into_iter().collect::<Vec<_>>()).into();

        let promise = unsafe { q::JS_Ext_PromiseAny(context.context, iterable.value) };
        let promise = OwnedJsValue::new(context.context, promise);

        ensure_no_excpetion(context.context)?;

        Ok(OwnedJsPromise::try_from_value(promise)?)
    }

    pub fn with_resolvers(
        context: &Context,
    ) -> Result<(OwnedJsPromise, JsFunction, JsFunction), ExecutionError> {
        let obj = unsafe { q::JS_Ext_PromiseWithResolvers(context.context) };
        let obj = OwnedJsValue::new(context.context, obj);

        ensure_no_excpetion(context.context)?;

        let obj = obj.try_into_object()?;

        // use .unwrap() here because the fields are guaranteed to be there
        let promise = obj.property("promise")?.unwrap().try_into_promise()?;
        let resolve = obj.property("resolve")?.unwrap().try_into_function()?;
        let reject = obj.property("reject")?.unwrap().try_into_function()?;

        Ok((promise, resolve, reject))
    }
}

impl Deref for OwnedJsPromise {
    type Target = OwnedJsValue;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

#[derive(Debug, Clone, Copy)]
pub enum PromiseState {
    Pending,
    Fulfilled,
    Rejected,
}