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