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