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
130// `FromWasmAbi` is what the closure shim invokes on the resolved value;
131// no layout equivalence with `JsValue` is required at this seam — the
132// per-type `from_abi` does the conversion (e.g. for dynamic unions it
133// runs the variant dispatcher).
134impl<T: FromWasmAbi + 'static> From<Promise<T>> for JsFuture<T> {
135 fn from(js: Promise<T>) -> JsFuture<T> {
136 // Use the `then` method to schedule two callbacks, one for the
137 // resolved value and one for the rejected value. We're currently
138 // assuming that JS engines will unconditionally invoke precisely one of
139 // these callbacks, no matter what.
140 //
141 // Ideally we'd have a way to cancel the callbacks getting invoked and
142 // free up state ourselves when this `JsFuture` is dropped. We don't
143 // have that, though, and one of the callbacks is likely always going to
144 // be invoked.
145 //
146 // As a result we need to make sure that no matter when the callbacks
147 // are invoked they are valid to be called at any time, which means they
148 // have to be self-contained. Through the `Closure::once` and some
149 // `Rc`-trickery we can arrange for both instances of `Closure`, and the
150 // `Rc`, to all be destroyed once the first one is called.
151 let state = Rc::new(RefCell::new(Inner::<T> {
152 result: None,
153 task: None,
154 callbacks: None,
155 }));
156
157 fn finish<T>(state: &RefCell<Inner<T>>, val: Result<T, JsValue>) {
158 let task = {
159 let mut state = state.borrow_mut();
160 assert!(
161 state.callbacks.is_some(),
162 "finish: callbacks should be Some"
163 );
164 assert!(state.result.is_none(), "finish: result should be None");
165
166 // First up drop our closures as they'll never be invoked again and
167 // this is our chance to clean up their state.
168 drop(state.callbacks.take());
169
170 // Next, store the value into the internal state.
171 state.result = Some(val);
172 state.task.take()
173 };
174
175 // And then finally if any task was waiting on the value wake it up and
176 // let them know it's there.
177 if let Some(task) = task {
178 task.wake()
179 }
180 }
181
182 let resolve = {
183 let state = AssertUnwindSafe(state.clone());
184 Closure::once(move |val: T| {
185 finish(&*state, Ok(val));
186 Ok(())
187 })
188 };
189
190 let reject = {
191 let state = AssertUnwindSafe(state.clone());
192 Closure::once(move |val| {
193 finish(&*state, Err(val));
194 Ok(())
195 })
196 };
197
198 let _ = js.then_with_reject(&resolve, &reject);
199
200 state.borrow_mut().callbacks = Some((resolve, reject));
201
202 JsFuture { inner: state }
203 }
204}
205
206impl<T> Future for JsFuture<T> {
207 type Output = Result<T, JsValue>;
208
209 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
210 let mut inner = self.inner.borrow_mut();
211
212 // If our value has come in then we return it...
213 if let Some(val) = inner.result.take() {
214 return Poll::Ready(val);
215 }
216
217 // ... otherwise we arrange ourselves to get woken up once the value
218 // does come in
219 inner.task = Some(cx.waker().clone());
220 Poll::Pending
221 }
222}
223
224impl<T: FromWasmAbi + 'static> IntoFuture for Promise<T> {
225 type Output = Result<T, JsValue>;
226 type IntoFuture = JsFuture<T>;
227
228 fn into_future(self) -> JsFuture<T> {
229 JsFuture::from(self)
230 }
231}
232
233/// Converts a Rust `Future` into a JavaScript `Promise`.
234///
235/// This function will take any future in Rust and schedule it to be executed,
236/// returning a JavaScript `Promise` which can then be passed to JavaScript.
237///
238/// The `future` must be `'static` because it will be scheduled to run in the
239/// background and cannot contain any stack references.
240///
241/// The returned `Promise` will be resolved or rejected when the future
242/// completes, depending on whether it finishes with `Ok` or `Err`.
243///
244/// # Panics
245///
246/// Note that in Wasm panics are currently translated to aborts, but "abort" in
247/// this case means that a JavaScript exception is thrown. The Wasm module is
248/// still usable (likely erroneously) after Rust panics.
249#[cfg(not(all(target_family = "wasm", feature = "std", panic = "unwind")))]
250pub fn future_to_promise<F>(future: F) -> Promise
251where
252 F: Future<Output = Result<JsValue, JsValue>> + 'static,
253{
254 let mut future = Some(future);
255
256 Promise::new_typed(&mut move |resolve, reject| {
257 let future = future.take().unwrap_throw();
258
259 spawn_local(async move {
260 match future.await {
261 Ok(val) => {
262 resolve.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
263 }
264 Err(val) => {
265 reject.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
266 }
267 }
268 });
269 })
270}
271
272/// Converts a Rust `Future` into a JavaScript `Promise`.
273///
274/// This function will take any future in Rust and schedule it to be executed,
275/// returning a JavaScript `Promise` which can then be passed to JavaScript.
276///
277/// The `future` must be `'static` because it will be scheduled to run in the
278/// background and cannot contain any stack references.
279///
280/// The returned `Promise` will be resolved or rejected when the future
281/// completes, depending on whether it finishes with `Ok` or `Err`.
282///
283/// # Panics
284///
285/// If the `future` provided panics then the returned `Promise` will be rejected
286/// with a PanicError.
287#[cfg(all(target_family = "wasm", feature = "std", panic = "unwind"))]
288pub fn future_to_promise<F>(future: F) -> Promise
289where
290 F: Future<Output = Result<JsValue, JsValue>> + 'static + std::panic::UnwindSafe,
291{
292 // Wrap `future` in AssertUnwindSafe and move it into the closure so the closure
293 // satisfies MaybeUnwindSafe (required when panic=unwind). Using `move` avoids
294 // capturing a `&mut` reference, which is never UnwindSafe. The Promise executor
295 // is not called inside a panic-catching context, so this is always safe.
296 let mut future = core::panic::AssertUnwindSafe(Some(future));
297 Promise::new(&mut move |resolve, reject| {
298 let future = future.take().unwrap_throw();
299 spawn_local(async move {
300 let res = future.catch_unwind().await;
301 match res {
302 Ok(Ok(val)) => {
303 resolve.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
304 }
305 Ok(Err(val)) => {
306 reject.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
307 }
308 Err(val) => {
309 reject
310 .call(&JsValue::UNDEFINED, (&panic_to_panic_error(val),))
311 .unwrap_throw();
312 }
313 }
314 });
315 })
316}
317
318// Note: Once we bump MSRV, we can type future_to_promise with backwards compatible inference.
319/// Converts a Rust `Future` into a corresponding typed JavaScript `Promise<T>`.
320///
321/// This function will take any future in Rust and schedule it to be executed,
322/// returning a JavaScript `Promise` which can then be passed to JavaScript.
323///
324/// The `future` must be `'static` because it will be scheduled to run in the
325/// background and cannot contain any stack references.
326///
327/// The returned `Promise` will be resolved or rejected when the future completes,
328/// depending on whether it finishes with `Ok` or `Err`.
329///
330/// # Panics
331///
332/// Note that in Wasm panics are currently translated to aborts, but "abort" in
333/// this case means that a JavaScript exception is thrown. The Wasm module is
334/// still usable (likely erroneously) after Rust panics.
335///
336/// If the `future` provided panics then the returned `Promise` **will not
337/// resolve**. Instead it will be a leaked promise. This is an unfortunate
338/// limitation of Wasm currently that's hoped to be fixed one day!
339pub fn future_to_promise_typed<T, F>(future: F) -> Promise<<T as Promising>::Resolution>
340where
341 F: Future<Output = Result<T, JsValue>> + 'static,
342 T: Promising + FromWasmAbi + JsGeneric,
343 <T as Promising>::Resolution: JsGeneric,
344{
345 let mut future = Some(future);
346
347 Promise::new_typed(&mut move |resolve, reject| {
348 let future = future.take().unwrap_throw();
349 spawn_local(async move {
350 match future.await {
351 Ok(val) => {
352 resolve.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
353 }
354 Err(val) => {
355 reject.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
356 }
357 }
358 });
359 })
360}