Merge pull request #1148 from derekdreery/spawn_local

Spawn local
This commit is contained in:
Alex Crichton 2019-01-07 10:27:44 -06:00 committed by GitHub
commit 194a169c24
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 38 additions and 1 deletions

View File

@ -377,3 +377,22 @@ fn _future_to_promise(future: Box<Future<Item = JsValue, Error = JsValue>>) -> P
}
}
}
/// Converts a Rust `Future` on a local task queue.
///
/// The `future` provided must adhere to `'static` because it'll be scheduled
/// to run in the background and cannot contain any stack references.
///
/// # Panics
///
/// This function has the same panic behavior as `future_to_promise`.
pub fn spawn_local<F>(future: F)
where
F: Future<Item=(), Error=()> + 'static,
{
future_to_promise(
future
.map(|()| JsValue::undefined())
.map_err(|()| JsValue::undefined()),
);
}

View File

@ -9,7 +9,7 @@ extern crate wasm_bindgen_test;
use futures::unsync::oneshot;
use futures::Future;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::{future_to_promise, JsFuture};
use wasm_bindgen_futures::{future_to_promise, spawn_local, JsFuture};
use wasm_bindgen_test::*;
#[wasm_bindgen_test(async)]
@ -68,3 +68,21 @@ fn oneshot_works() -> impl Future<Item = (), Error = JsValue> {
closure.forget();
rx.then(|_| Ok(()))
}
#[wasm_bindgen_test(async)]
fn spawn_local_runs() -> impl Future<Item = (), Error = JsValue> {
let (tx, rx) = oneshot::channel::<u32>();
let fn_box = Box::new(move || {
tx.send(42).unwrap();
});
spawn_local(futures::future::ok::<(), ()>(()).map(|_| {
fn_box();
}));
rx.then(|val| {
if val == Ok(42) {
Ok(())
} else {
Err(JsValue::undefined())
}
})
}