justauser
justauser

Reputation: 53

use blockon in rust wasm

i want to use block_on in rust when compiling to wasm. The problem is i am using egui and want to compile it to web. Its function are sync and i need to block async functions. I tried with async_futures, but it seems to start the future, but not blocking it.

#[wasm_bindgen]
pub fn test1() {
    alert("Hello, 1");

    async_std::task::block_on(async {
        alert("Hello, 2");
        async_std::task::sleep(Duration::from_secs(5)).await;
        alert("Hello, 3");
    });

    alert("Hello, 4");
}

The output would be in order 1, 4, 2, 3.

It does not emit any binding which i could use to check if its done and i cant pass in a mutex since i would need to await it outside of the async code which is not possible. Any idea how to block it?

I was expecting the output 1, 2, 3, 4

Upvotes: 5

Views: 964

Answers (2)

Ddystopia
Ddystopia

Reputation: 67

You may use crate pollster

use pollster::FutureExt as _;

let my_fut = async {};

let result = my_fut.block_on();

Upvotes: 1

frankenapps
frankenapps

Reputation: 8241

It is not possible to run blocking code in a webbrowser.

Browser vendors do not allow this. It is basically the same as in javascript.

If this would be possible, it would be a way to run asynchronous code in a synchronous JavaScript function (since test1 will be invoked from JavaScript) which is not permitted.

This is also an open issue in async-std (note that the mention of pollster seems to be incorrect, as it panicked on the .awaited statement when I tried to use pollster::block_on).

Upvotes: 2

Related Questions