wasm_bindgen_futures/
lib.rs

1//! Converting between JavaScript `Promise`s to Rust `Future`s.
2//!
3//! This crate 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 crate 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
33#![cfg_attr(not(feature = "std"), no_std)]
34#![cfg_attr(
35    target_feature = "atomics",
36    feature(thread_local, stdarch_wasm_atomic_wait)
37)]
38#![deny(missing_docs)]
39#![cfg_attr(docsrs, feature(doc_cfg))]
40
41extern crate alloc;
42
43use alloc::rc::Rc;
44use core::cell::RefCell;
45use core::fmt;
46use core::future::Future;
47use core::pin::Pin;
48use core::task::{Context, Poll, Waker};
49use js_sys::Promise;
50use wasm_bindgen::prelude::*;
51
52mod queue;
53#[cfg_attr(docsrs, doc(cfg(feature = "futures-core-03-stream")))]
54#[cfg(feature = "futures-core-03-stream")]
55pub mod stream;
56
57pub use js_sys;
58pub use wasm_bindgen;
59
60mod task {
61    use cfg_if::cfg_if;
62
63    cfg_if! {
64        if #[cfg(target_feature = "atomics")] {
65            mod wait_async_polyfill;
66            mod multithread;
67            pub(crate) use multithread::*;
68
69        } else {
70            mod singlethread;
71            pub(crate) use singlethread::*;
72         }
73    }
74}
75
76/// Runs a Rust `Future` on the current thread.
77///
78/// The `future` must be `'static` because it will be scheduled
79/// to run in the background and cannot contain any stack references.
80///
81/// The `future` will always be run on the next microtask tick even if it
82/// immediately returns `Poll::Ready`.
83///
84/// # Panics
85///
86/// This function has the same panic behavior as `future_to_promise`.
87#[inline]
88pub fn spawn_local<F>(future: F)
89where
90    F: Future<Output = ()> + 'static,
91{
92    task::Task::spawn(future);
93}
94
95struct Inner {
96    result: Option<Result<JsValue, JsValue>>,
97    task: Option<Waker>,
98    callbacks: Option<(Closure<dyn FnMut(JsValue)>, Closure<dyn FnMut(JsValue)>)>,
99}
100
101/// A Rust `Future` backed by a JavaScript `Promise`.
102///
103/// This type is constructed with a JavaScript `Promise` object and translates
104/// it to a Rust `Future`. This type implements the `Future` trait from the
105/// `futures` crate and will either succeed or fail depending on what happens
106/// with the JavaScript `Promise`.
107///
108/// Currently this type is constructed with `JsFuture::from`.
109pub struct JsFuture {
110    inner: Rc<RefCell<Inner>>,
111}
112
113impl fmt::Debug for JsFuture {
114    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
115        write!(f, "JsFuture {{ ... }}")
116    }
117}
118
119impl From<Promise> for JsFuture {
120    fn from(js: Promise) -> JsFuture {
121        // Use the `then` method to schedule two callbacks, one for the
122        // resolved value and one for the rejected value. We're currently
123        // assuming that JS engines will unconditionally invoke precisely one of
124        // these callbacks, no matter what.
125        //
126        // Ideally we'd have a way to cancel the callbacks getting invoked and
127        // free up state ourselves when this `JsFuture` is dropped. We don't
128        // have that, though, and one of the callbacks is likely always going to
129        // be invoked.
130        //
131        // As a result we need to make sure that no matter when the callbacks
132        // are invoked they are valid to be called at any time, which means they
133        // have to be self-contained. Through the `Closure::once` and some
134        // `Rc`-trickery we can arrange for both instances of `Closure`, and the
135        // `Rc`, to all be destroyed once the first one is called.
136        let state = Rc::new(RefCell::new(Inner {
137            result: None,
138            task: None,
139            callbacks: None,
140        }));
141
142        fn finish(state: &RefCell<Inner>, val: Result<JsValue, JsValue>) {
143            let task = {
144                let mut state = state.borrow_mut();
145                debug_assert!(state.callbacks.is_some());
146                debug_assert!(state.result.is_none());
147
148                // First up drop our closures as they'll never be invoked again and
149                // this is our chance to clean up their state.
150                drop(state.callbacks.take());
151
152                // Next, store the value into the internal state.
153                state.result = Some(val);
154                state.task.take()
155            };
156
157            // And then finally if any task was waiting on the value wake it up and
158            // let them know it's there.
159            if let Some(task) = task {
160                task.wake()
161            }
162        }
163
164        let resolve = {
165            let state = state.clone();
166            Closure::once(move |val| finish(&state, Ok(val)))
167        };
168
169        let reject = {
170            let state = state.clone();
171            Closure::once(move |val| finish(&state, Err(val)))
172        };
173
174        let _ = js.then2(&resolve, &reject);
175
176        state.borrow_mut().callbacks = Some((resolve, reject));
177
178        JsFuture { inner: state }
179    }
180}
181
182impl Future for JsFuture {
183    type Output = Result<JsValue, JsValue>;
184
185    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
186        let mut inner = self.inner.borrow_mut();
187
188        // If our value has come in then we return it...
189        if let Some(val) = inner.result.take() {
190            return Poll::Ready(val);
191        }
192
193        // ... otherwise we arrange ourselves to get woken up once the value
194        // does come in
195        inner.task = Some(cx.waker().clone());
196        Poll::Pending
197    }
198}
199
200/// Converts a Rust `Future` into a JavaScript `Promise`.
201///
202/// This function will take any future in Rust and schedule it to be executed,
203/// returning a JavaScript `Promise` which can then be passed to JavaScript.
204///
205/// The `future` must be `'static` because it will be scheduled to run in the
206/// background and cannot contain any stack references.
207///
208/// The returned `Promise` will be resolved or rejected when the future completes,
209/// depending on whether it finishes with `Ok` or `Err`.
210///
211/// # Panics
212///
213/// Note that in Wasm panics are currently translated to aborts, but "abort" in
214/// this case means that a JavaScript exception is thrown. The Wasm module is
215/// still usable (likely erroneously) after Rust panics.
216///
217/// If the `future` provided panics then the returned `Promise` **will not
218/// resolve**. Instead it will be a leaked promise. This is an unfortunate
219/// limitation of Wasm currently that's hoped to be fixed one day!
220pub fn future_to_promise<F>(future: F) -> Promise
221where
222    F: Future<Output = Result<JsValue, JsValue>> + 'static,
223{
224    let mut future = Some(future);
225
226    Promise::new(&mut |resolve, reject| {
227        let future = future.take().unwrap_throw();
228
229        spawn_local(async move {
230            match future.await {
231                Ok(val) => {
232                    resolve.call1(&JsValue::undefined(), &val).unwrap_throw();
233                }
234                Err(val) => {
235                    reject.call1(&JsValue::undefined(), &val).unwrap_throw();
236                }
237            }
238        });
239    })
240}