Skip to main content

js_sys/futures/
mod.rs

1//! Converting between JavaScript `Promise`s to Rust `Future`s.
2//!
3//! This module provides a bridge for working with JavaScript `Promise` types as
4//! a Rust `Future`, and similarly contains utilities to turn a rust `Future`
5//! into a JavaScript `Promise`. This can be useful when working with
6//! asynchronous or otherwise blocking work in Rust (wasm), and provides the
7//! ability to interoperate with JavaScript events and JavaScript I/O
8//! primitives.
9//!
10//! There are three main interfaces in this module currently:
11//!
12//! 1. [**`JsFuture`**](./struct.JsFuture.html)
13//!
14//!    A type that is constructed with a `Promise` and can then be used as a
15//!    `Future<Output = Result<JsValue, JsValue>>`. This Rust future will resolve
16//!    or reject with the value coming out of the `Promise`.
17//!
18//! 2. [**`future_to_promise`**](./fn.future_to_promise.html)
19//!
20//!    Converts a Rust `Future<Output = Result<JsValue, JsValue>>` into a
21//!    JavaScript `Promise`. The future's result will translate to either a
22//!    resolved or rejected `Promise` in JavaScript.
23//!
24//! 3. [**`spawn_local`**](./fn.spawn_local.html)
25//!
26//!    Spawns a `Future<Output = ()>` on the current thread. This is the
27//!    best way to run a `Future` in Rust without sending it to JavaScript.
28//!
29//! These three items should provide enough of a bridge to interoperate the two
30//! systems and make sure that Rust/JavaScript can work together with
31//! asynchronous and I/O work.
32
33extern crate alloc;
34
35use crate::Promise;
36use alloc::rc::Rc;
37use core::cell::RefCell;
38use core::fmt;
39use core::future::{Future, IntoFuture};
40use core::panic::AssertUnwindSafe;
41use core::pin::Pin;
42use core::task::{Context, Poll, Waker};
43#[cfg(all(target_family = "wasm", feature = "std", panic = "unwind"))]
44use futures_util::FutureExt;
45use wasm_bindgen::__rt::marker::ErasableGeneric;
46#[cfg(all(target_family = "wasm", feature = "std", panic = "unwind"))]
47use wasm_bindgen::__rt::panic_to_panic_error;
48use wasm_bindgen::convert::{FromWasmAbi, Upcast};
49use wasm_bindgen::sys::Promising;
50use wasm_bindgen::{prelude::*, JsError, JsGeneric};
51
52#[cfg_attr(docsrs, doc(cfg(feature = "futures-core-03-stream")))]
53#[cfg(feature = "futures-core-03-stream")]
54pub mod stream;
55
56mod queue;
57
58mod task {
59    use cfg_if::cfg_if;
60
61    cfg_if! {
62        if #[cfg(target_feature = "atomics")] {
63            mod wait_async_polyfill;
64            mod multithread;
65            pub(crate) use multithread::*;
66
67        } else {
68            mod singlethread;
69            pub(crate) use singlethread::*;
70         }
71    }
72}
73
74/// Runs a Rust `Future` on the current thread.
75///
76/// The `future` must be `'static` because it will be scheduled
77/// to run in the background and cannot contain any stack references.
78///
79/// The `future` will always be run on the next microtask tick even if it
80/// immediately returns `Poll::Ready`.
81///
82/// # Panics
83///
84/// This function has the same panic behavior as `future_to_promise`.
85#[inline]
86pub fn spawn_local<F>(future: F)
87where
88    F: Future<Output = ()> + 'static,
89{
90    task::Task::spawn(future);
91}
92
93struct Inner<T = JsValue> {
94    result: Option<Result<T, JsValue>>,
95    task: Option<Waker>,
96    callbacks: Option<(
97        Closure<dyn FnMut(T) -> Result<(), JsError>>,
98        Closure<dyn FnMut(JsValue) -> Result<(), JsError>>,
99    )>,
100}
101
102/// A Rust `Future` backed by a JavaScript `Promise`.
103///
104/// This type is constructed with a JavaScript `Promise` object and translates
105/// it to a Rust `Future`. This type implements the `Future` trait from the
106/// `futures` crate and will either succeed or fail depending on what happens
107/// with the JavaScript `Promise`.
108///
109/// Currently this type is constructed with `JsFuture::from`.
110pub struct JsFuture<T = JsValue> {
111    inner: Rc<RefCell<Inner<T>>>,
112}
113
114impl core::panic::UnwindSafe for JsFuture {}
115
116unsafe impl<T> ErasableGeneric for JsFuture<T> {
117    type Repr = JsFuture<JsValue>;
118}
119
120// Upcast for JsFuture is covariant in T (the success type)
121// JsFuture<T> can upcast to JsFuture<Target> if T: Upcast<Target>
122impl<T, Target> Upcast<JsFuture<Target>> for JsFuture<T> where T: Upcast<Target> {}
123
124impl<T> fmt::Debug for JsFuture<T> {
125    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
126        write!(f, "JsFuture {{ ... }}")
127    }
128}
129
130impl<T: JsGeneric + FromWasmAbi> From<Promise<T>> for JsFuture<T> {
131    fn from(js: Promise<T>) -> JsFuture<T> {
132        // Use the `then` method to schedule two callbacks, one for the
133        // resolved value and one for the rejected value. We're currently
134        // assuming that JS engines will unconditionally invoke precisely one of
135        // these callbacks, no matter what.
136        //
137        // Ideally we'd have a way to cancel the callbacks getting invoked and
138        // free up state ourselves when this `JsFuture` is dropped. We don't
139        // have that, though, and one of the callbacks is likely always going to
140        // be invoked.
141        //
142        // As a result we need to make sure that no matter when the callbacks
143        // are invoked they are valid to be called at any time, which means they
144        // have to be self-contained. Through the `Closure::once` and some
145        // `Rc`-trickery we can arrange for both instances of `Closure`, and the
146        // `Rc`, to all be destroyed once the first one is called.
147        let state = Rc::new(RefCell::new(Inner::<T> {
148            result: None,
149            task: None,
150            callbacks: None,
151        }));
152
153        fn finish<T>(state: &RefCell<Inner<T>>, val: Result<T, JsValue>) {
154            let task = {
155                let mut state = state.borrow_mut();
156                assert!(
157                    state.callbacks.is_some(),
158                    "finish: callbacks should be Some"
159                );
160                assert!(state.result.is_none(), "finish: result should be None");
161
162                // First up drop our closures as they'll never be invoked again and
163                // this is our chance to clean up their state.
164                drop(state.callbacks.take());
165
166                // Next, store the value into the internal state.
167                state.result = Some(val);
168                state.task.take()
169            };
170
171            // And then finally if any task was waiting on the value wake it up and
172            // let them know it's there.
173            if let Some(task) = task {
174                task.wake()
175            }
176        }
177
178        let resolve = {
179            let state = AssertUnwindSafe(state.clone());
180            Closure::once(move |val: T| {
181                finish(&*state, Ok(val));
182                Ok(())
183            })
184        };
185
186        let reject = {
187            let state = AssertUnwindSafe(state.clone());
188            Closure::once(move |val| {
189                finish(&*state, Err(val));
190                Ok(())
191            })
192        };
193
194        let _ = js.then_with_reject(&resolve, &reject);
195
196        state.borrow_mut().callbacks = Some((resolve, reject));
197
198        JsFuture { inner: state }
199    }
200}
201
202impl<T> Future for JsFuture<T> {
203    type Output = Result<T, JsValue>;
204
205    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
206        let mut inner = self.inner.borrow_mut();
207
208        // If our value has come in then we return it...
209        if let Some(val) = inner.result.take() {
210            return Poll::Ready(val);
211        }
212
213        // ... otherwise we arrange ourselves to get woken up once the value
214        // does come in
215        inner.task = Some(cx.waker().clone());
216        Poll::Pending
217    }
218}
219
220impl<T: JsGeneric + FromWasmAbi> IntoFuture for Promise<T> {
221    type Output = Result<T, JsValue>;
222    type IntoFuture = JsFuture<T>;
223
224    fn into_future(self) -> JsFuture<T> {
225        JsFuture::from(self)
226    }
227}
228
229/// Converts a Rust `Future` into a JavaScript `Promise`.
230///
231/// This function will take any future in Rust and schedule it to be executed,
232/// returning a JavaScript `Promise` which can then be passed to JavaScript.
233///
234/// The `future` must be `'static` because it will be scheduled to run in the
235/// background and cannot contain any stack references.
236///
237/// The returned `Promise` will be resolved or rejected when the future
238/// completes, depending on whether it finishes with `Ok` or `Err`.
239///
240/// # Panics
241///
242/// Note that in Wasm panics are currently translated to aborts, but "abort" in
243/// this case means that a JavaScript exception is thrown. The Wasm module is
244/// still usable (likely erroneously) after Rust panics.
245#[cfg(not(all(target_family = "wasm", feature = "std", panic = "unwind")))]
246pub fn future_to_promise<F>(future: F) -> Promise
247where
248    F: Future<Output = Result<JsValue, JsValue>> + 'static,
249{
250    let mut future = Some(future);
251
252    Promise::new_typed(&mut move |resolve, reject| {
253        let future = future.take().unwrap_throw();
254
255        spawn_local(async move {
256            match future.await {
257                Ok(val) => {
258                    resolve.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
259                }
260                Err(val) => {
261                    reject.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
262                }
263            }
264        });
265    })
266}
267
268/// Converts a Rust `Future` into a JavaScript `Promise`.
269///
270/// This function will take any future in Rust and schedule it to be executed,
271/// returning a JavaScript `Promise` which can then be passed to JavaScript.
272///
273/// The `future` must be `'static` because it will be scheduled to run in the
274/// background and cannot contain any stack references.
275///
276/// The returned `Promise` will be resolved or rejected when the future
277/// completes, depending on whether it finishes with `Ok` or `Err`.
278///
279/// # Panics
280///
281/// If the `future` provided panics then the returned `Promise` will be rejected
282/// with a PanicError.
283#[cfg(all(target_family = "wasm", feature = "std", panic = "unwind"))]
284pub fn future_to_promise<F>(future: F) -> Promise
285where
286    F: Future<Output = Result<JsValue, JsValue>> + 'static + std::panic::UnwindSafe,
287{
288    // Wrap `future` in AssertUnwindSafe and move it into the closure so the closure
289    // satisfies MaybeUnwindSafe (required when panic=unwind). Using `move` avoids
290    // capturing a `&mut` reference, which is never UnwindSafe. The Promise executor
291    // is not called inside a panic-catching context, so this is always safe.
292    let mut future = core::panic::AssertUnwindSafe(Some(future));
293    Promise::new(&mut move |resolve, reject| {
294        let future = future.take().unwrap_throw();
295        spawn_local(async move {
296            let res = future.catch_unwind().await;
297            match res {
298                Ok(Ok(val)) => {
299                    resolve.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
300                }
301                Ok(Err(val)) => {
302                    reject.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
303                }
304                Err(val) => {
305                    reject
306                        .call(&JsValue::UNDEFINED, (&panic_to_panic_error(val),))
307                        .unwrap_throw();
308                }
309            }
310        });
311    })
312}
313
314// Note: Once we bump MSRV, we can type future_to_promise with backwards compatible inference.
315/// Converts a Rust `Future` into a corresponding typed JavaScript `Promise<T>`.
316///
317/// This function will take any future in Rust and schedule it to be executed,
318/// returning a JavaScript `Promise` which can then be passed to JavaScript.
319///
320/// The `future` must be `'static` because it will be scheduled to run in the
321/// background and cannot contain any stack references.
322///
323/// The returned `Promise` will be resolved or rejected when the future completes,
324/// depending on whether it finishes with `Ok` or `Err`.
325///
326/// # Panics
327///
328/// Note that in Wasm panics are currently translated to aborts, but "abort" in
329/// this case means that a JavaScript exception is thrown. The Wasm module is
330/// still usable (likely erroneously) after Rust panics.
331///
332/// If the `future` provided panics then the returned `Promise` **will not
333/// resolve**. Instead it will be a leaked promise. This is an unfortunate
334/// limitation of Wasm currently that's hoped to be fixed one day!
335pub fn future_to_promise_typed<T, F>(future: F) -> Promise<<T as Promising>::Resolution>
336where
337    F: Future<Output = Result<T, JsValue>> + 'static,
338    T: Promising + FromWasmAbi + JsGeneric,
339    <T as Promising>::Resolution: JsGeneric,
340{
341    let mut future = Some(future);
342
343    Promise::new_typed(&mut move |resolve, reject| {
344        let future = future.take().unwrap_throw();
345        spawn_local(async move {
346            match future.await {
347                Ok(val) => {
348                    resolve.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
349                }
350                Err(val) => {
351                    reject.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
352                }
353            }
354        });
355    })
356}