Skip to content

Commit

Permalink
Add naive spawn_local implementation + tests
Browse files Browse the repository at this point in the history
This is just a naive implementation. It seems it can be improved using a
custom task queue, but that can be in a separate PR.
  • Loading branch information
richard-uk1 committed Jan 5, 2019
1 parent 1758c8d commit c849ef3
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
12 changes: 12 additions & 0 deletions crates/futures/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -377,3 +377,15 @@ fn _future_to_promise(future: Box<Future<Item = JsValue, Error = JsValue>>) -> P
}
}
}

/// Spawns a future.
pub fn spawn_local<F>(future: F)
where
F: Future<Item = (), Error = ()> + 'static,
{
future_to_promise(
future
.map(|_| JsValue::undefined())
.map_err(|_| JsValue::undefined()),
);
}
20 changes: 19 additions & 1 deletion crates/futures/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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())
}
})
}

0 comments on commit c849ef3

Please sign in to comment.