Skip to main content

main_loop_async/
yield_.rs

1/// Attempts to provide a yield for executor currently in use.
2///
3/// There doesn't appear to be one available as yet for `wasm_bindgen_futures`
4/// so a workaround taken from
5/// <https://github.com/rustwasm/wasm-bindgen/discussions/3476> is used
6pub async fn yield_now() {
7    #[cfg(target_arch = "wasm32")]
8    sleep_ms(1).await;
9    #[cfg(not(target_arch = "wasm32"))]
10    tokio::task::yield_now().await;
11}
12
13#[cfg(target_arch = "wasm32")]
14// Hack to get async sleep on wasm
15// Taken from https://github.com/rustwasm/wasm-bindgen/discussions/3476
16async fn sleep_ms(millis: i32) {
17    let mut cb = |resolve: js_sys::Function, _reject: js_sys::Function| {
18        web_sys::window()
19            .unwrap()
20            .set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, millis)
21            .expect("Failed to call set_timeout");
22    };
23    let p = js_sys::Promise::new(&mut cb);
24    wasm_bindgen_futures::JsFuture::from(p).await.unwrap();
25}