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
35#[cfg(not(target_feature = "atomics"))]
36mod jspi;
37
38use crate::Promise;
39use alloc::rc::Rc;
40use core::cell::RefCell;
41use core::fmt;
42use core::future::{Future, IntoFuture};
43use core::panic::AssertUnwindSafe;
44use core::pin::Pin;
45use core::task::{Context, Poll, Waker};
46#[cfg(all(
47    all(target_family = "wasm", not(target_os = "wasi")),
48    feature = "std",
49    panic = "unwind"
50))]
51use futures_util::FutureExt;
52use wasm_bindgen::__rt::marker::ErasableGeneric;
53#[cfg(all(
54    all(target_family = "wasm", not(target_os = "wasi")),
55    feature = "std",
56    panic = "unwind"
57))]
58use wasm_bindgen::__rt::panic_to_panic_error;
59use wasm_bindgen::convert::{FromWasmAbi, Upcast};
60use wasm_bindgen::sys::Promising;
61use wasm_bindgen::{prelude::*, JsError, JsGeneric};
62
63#[cfg_attr(docsrs, doc(cfg(feature = "futures-core-03-stream")))]
64#[cfg(feature = "futures-core-03-stream")]
65pub mod stream;
66
67mod queue;
68
69mod task {
70    use cfg_if::cfg_if;
71
72    cfg_if! {
73        if #[cfg(target_feature = "atomics")] {
74            mod wait_async_polyfill;
75            mod multithread;
76            pub(crate) use multithread::*;
77
78        } else {
79            mod singlethread;
80            pub(crate) use singlethread::*;
81         }
82    }
83}
84
85/// Runs a Rust `Future` on the current thread.
86///
87/// The `future` must be `'static` because it will be scheduled
88/// to run in the background and cannot contain any stack references.
89///
90/// The `future` will always be run on the next microtask tick even if it
91/// immediately returns `Poll::Ready`.
92///
93/// # JSPI
94///
95/// When called from within a JSPI context — a `#[wasm_bindgen(jspi)]` export
96/// or a task itself spawned from one — the task's polls are entered through
97/// a `WebAssembly.promising` boundary, so sync code reached from the future
98/// may suspend via [`jspi_block_on_promise`]. The capability is inherited
99/// transitively down the spawn tree; a suspension parks only that task's
100/// poll. In modules that never use JSPI attributes this branch compiles to a
101/// constant and no JSPI machinery is emitted.
102///
103/// # Panics
104///
105/// This function has the same panic behavior as `future_to_promise`.
106#[inline]
107pub fn spawn_local<F>(future: F)
108where
109    F: Future<Output = ()> + 'static,
110{
111    #[cfg(not(target_feature = "atomics"))]
112    if jspi::in_context() {
113        jspi::spawn_promising(future);
114        return;
115    }
116    task::Task::spawn(future);
117}
118
119/// Suspend the current JSPI execution until `promise` settles, returning the
120/// resolved value as `Ok` or the rejection reason as `Err` — without
121/// blocking the event loop, and without an `async` call chain.
122///
123/// May only be called where a `WebAssembly.promising` frame is on the stack:
124/// within a `#[wasm_bindgen(jspi)]` export, or a task spawned (transitively)
125/// from a JSPI context. Calling it elsewhere throws a `SuspendError` at
126/// runtime.
127///
128/// Promises are eager, so concurrency composes at the promise level: start
129/// several JS calls, then suspend on each or on a `Promise::all` /
130/// `Promise::race` combination. A Rust `Future` is awaited by suspending on
131/// its completion promise: `jspi_block_on_promise(&future_to_promise(fut))`.
132#[cfg(not(target_feature = "atomics"))]
133#[deprecated(note = "JSPI support is experimental and subject to change; \
134            `jspi_block_on_promise` requires a runtime with WebAssembly \
135            JS Promise Integration enabled")]
136pub fn jspi_block_on_promise(promise: &Promise) -> Result<JsValue, JsValue> {
137    jspi::suspend(promise)
138}
139
140struct Inner<T = JsValue> {
141    result: Option<Result<T, JsValue>>,
142    task: Option<Waker>,
143    callbacks: Option<(
144        Closure<dyn FnMut(T) -> Result<(), JsError>>,
145        Closure<dyn FnMut(JsValue) -> Result<(), JsError>>,
146    )>,
147}
148
149/// A Rust `Future` backed by a JavaScript `Promise`.
150///
151/// This type is constructed with a JavaScript `Promise` object and translates
152/// it to a Rust `Future`. This type implements the `Future` trait from the
153/// `futures` crate and will either succeed or fail depending on what happens
154/// with the JavaScript `Promise`.
155///
156/// Currently this type is constructed with `JsFuture::from`.
157pub struct JsFuture<T = JsValue> {
158    inner: Rc<RefCell<Inner<T>>>,
159}
160
161impl core::panic::UnwindSafe for JsFuture {}
162
163unsafe impl<T> ErasableGeneric for JsFuture<T> {
164    type Repr = JsFuture<JsValue>;
165}
166
167// Upcast for JsFuture is covariant in T (the success type)
168// JsFuture<T> can upcast to JsFuture<Target> if T: Upcast<Target>
169impl<T, Target> Upcast<JsFuture<Target>> for JsFuture<T> where T: Upcast<Target> {}
170
171impl<T> fmt::Debug for JsFuture<T> {
172    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
173        write!(f, "JsFuture {{ ... }}")
174    }
175}
176
177// `FromWasmAbi` is what the closure shim invokes on the resolved value;
178// no layout equivalence with `JsValue` is required at this seam — the
179// per-type `from_abi` does the conversion (e.g. for dynamic unions it
180// runs the variant dispatcher).
181impl<T: FromWasmAbi + 'static> From<Promise<T>> for JsFuture<T> {
182    fn from(js: Promise<T>) -> JsFuture<T> {
183        // Use the `then` method to schedule two callbacks, one for the
184        // resolved value and one for the rejected value. We're currently
185        // assuming that JS engines will unconditionally invoke precisely one of
186        // these callbacks, no matter what.
187        //
188        // Ideally we'd have a way to cancel the callbacks getting invoked and
189        // free up state ourselves when this `JsFuture` is dropped. We don't
190        // have that, though, and one of the callbacks is likely always going to
191        // be invoked.
192        //
193        // As a result we need to make sure that no matter when the callbacks
194        // are invoked they are valid to be called at any time, which means they
195        // have to be self-contained. Through the `Closure::once` and some
196        // `Rc`-trickery we can arrange for both instances of `Closure`, and the
197        // `Rc`, to all be destroyed once the first one is called.
198        let state = Rc::new(RefCell::new(Inner::<T> {
199            result: None,
200            task: None,
201            callbacks: None,
202        }));
203
204        fn finish<T>(state: &RefCell<Inner<T>>, val: Result<T, JsValue>) {
205            let task = {
206                let mut state = state.borrow_mut();
207                assert!(
208                    state.callbacks.is_some(),
209                    "finish: callbacks should be Some"
210                );
211                assert!(state.result.is_none(), "finish: result should be None");
212
213                // First up drop our closures as they'll never be invoked again and
214                // this is our chance to clean up their state.
215                drop(state.callbacks.take());
216
217                // Next, store the value into the internal state.
218                state.result = Some(val);
219                state.task.take()
220            };
221
222            // And then finally if any task was waiting on the value wake it up and
223            // let them know it's there.
224            if let Some(task) = task {
225                task.wake()
226            }
227        }
228
229        let resolve = {
230            let state = AssertUnwindSafe(state.clone());
231            Closure::once(move |val: T| {
232                finish(&*state, Ok(val));
233                Ok(())
234            })
235        };
236
237        let reject = {
238            let state = AssertUnwindSafe(state.clone());
239            Closure::once(move |val| {
240                finish(&*state, Err(val));
241                Ok(())
242            })
243        };
244
245        let _ = js.then_with_reject(&resolve, &reject);
246
247        state.borrow_mut().callbacks = Some((resolve, reject));
248
249        JsFuture { inner: state }
250    }
251}
252
253impl<T> Future for JsFuture<T> {
254    type Output = Result<T, JsValue>;
255
256    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
257        let mut inner = self.inner.borrow_mut();
258
259        // If our value has come in then we return it...
260        if let Some(val) = inner.result.take() {
261            return Poll::Ready(val);
262        }
263
264        // ... otherwise we arrange ourselves to get woken up once the value
265        // does come in
266        inner.task = Some(cx.waker().clone());
267        Poll::Pending
268    }
269}
270
271impl<T: FromWasmAbi + 'static> IntoFuture for Promise<T> {
272    type Output = Result<T, JsValue>;
273    type IntoFuture = JsFuture<T>;
274
275    fn into_future(self) -> JsFuture<T> {
276        JsFuture::from(self)
277    }
278}
279
280/// Converts a Rust `Future` into a JavaScript `Promise`.
281///
282/// This function will take any future in Rust and schedule it to be executed,
283/// returning a JavaScript `Promise` which can then be passed to JavaScript.
284///
285/// The `future` must be `'static` because it will be scheduled to run in the
286/// background and cannot contain any stack references.
287///
288/// The returned `Promise` will be resolved or rejected when the future
289/// completes, depending on whether it finishes with `Ok` or `Err`.
290///
291/// # Panics
292///
293/// Note that in Wasm panics are currently translated to aborts, but "abort" in
294/// this case means that a JavaScript exception is thrown. The Wasm module is
295/// still usable (likely erroneously) after Rust panics.
296#[cfg(not(all(
297    all(target_family = "wasm", not(target_os = "wasi")),
298    feature = "std",
299    panic = "unwind"
300)))]
301pub fn future_to_promise<F>(future: F) -> Promise
302where
303    F: Future<Output = Result<JsValue, JsValue>> + 'static,
304{
305    let mut future = Some(future);
306
307    Promise::new_typed(&mut move |resolve, reject| {
308        let future = future.take().unwrap_throw();
309
310        spawn_local(async move {
311            match future.await {
312                Ok(val) => {
313                    resolve.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
314                }
315                Err(val) => {
316                    reject.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
317                }
318            }
319        });
320    })
321}
322
323/// Converts a Rust `Future` into a JavaScript `Promise`.
324///
325/// This function will take any future in Rust and schedule it to be executed,
326/// returning a JavaScript `Promise` which can then be passed to JavaScript.
327///
328/// The `future` must be `'static` because it will be scheduled to run in the
329/// background and cannot contain any stack references.
330///
331/// The returned `Promise` will be resolved or rejected when the future
332/// completes, depending on whether it finishes with `Ok` or `Err`.
333///
334/// # Panics
335///
336/// If the `future` provided panics then the returned `Promise` will be rejected
337/// with a PanicError.
338#[cfg(all(
339    all(target_family = "wasm", not(target_os = "wasi")),
340    feature = "std",
341    panic = "unwind"
342))]
343pub fn future_to_promise<F>(future: F) -> Promise
344where
345    F: Future<Output = Result<JsValue, JsValue>> + 'static + std::panic::UnwindSafe,
346{
347    // Wrap `future` in AssertUnwindSafe and move it into the closure so the closure
348    // satisfies MaybeUnwindSafe (required when panic=unwind). Using `move` avoids
349    // capturing a `&mut` reference, which is never UnwindSafe. The Promise executor
350    // is not called inside a panic-catching context, so this is always safe.
351    let mut future = core::panic::AssertUnwindSafe(Some(future));
352    Promise::new(&mut move |resolve, reject| {
353        let future = future.take().unwrap_throw();
354        spawn_local(async move {
355            let res = future.catch_unwind().await;
356            match res {
357                Ok(Ok(val)) => {
358                    resolve.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
359                }
360                Ok(Err(val)) => {
361                    reject.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
362                }
363                Err(val) => {
364                    reject
365                        .call(&JsValue::UNDEFINED, (&panic_to_panic_error(val),))
366                        .unwrap_throw();
367                }
368            }
369        });
370    })
371}
372
373// Note: Once we bump MSRV, we can type future_to_promise with backwards compatible inference.
374/// Converts a Rust `Future` into a corresponding typed JavaScript `Promise<T>`.
375///
376/// This function will take any future in Rust and schedule it to be executed,
377/// returning a JavaScript `Promise` which can then be passed to JavaScript.
378///
379/// The `future` must be `'static` because it will be scheduled to run in the
380/// background and cannot contain any stack references.
381///
382/// The returned `Promise` will be resolved or rejected when the future completes,
383/// depending on whether it finishes with `Ok` or `Err`.
384///
385/// # Panics
386///
387/// Note that in Wasm panics are currently translated to aborts, but "abort" in
388/// this case means that a JavaScript exception is thrown. The Wasm module is
389/// still usable (likely erroneously) after Rust panics.
390///
391/// If the `future` provided panics then the returned `Promise` **will not
392/// resolve**. Instead it will be a leaked promise. This is an unfortunate
393/// limitation of Wasm currently that's hoped to be fixed one day!
394pub fn future_to_promise_typed<T, F>(future: F) -> Promise<<T as Promising>::Resolution>
395where
396    F: Future<Output = Result<T, JsValue>> + 'static,
397    T: Promising + FromWasmAbi + JsGeneric,
398    <T as Promising>::Resolution: JsGeneric,
399{
400    let mut future = Some(future);
401
402    Promise::new_typed(&mut move |resolve, reject| {
403        let future = future.take().unwrap_throw();
404        spawn_local(async move {
405            match future.await {
406                Ok(val) => {
407                    resolve.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
408                }
409                Err(val) => {
410                    reject.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
411                }
412            }
413        });
414    })
415}