I am calling an async javascript function in rust/WASM. I would like to have the result in my rust function because I need to it to be synchronous.
Is there any ways to wait for the javascript function to resolve inside WASM ?
Here some code of what I am trying to do :
impl Transport for TransportJS {
fn exchange(&self) -> Result<Vec<u8>, Error> {
// Call the javscript function exchange
let promise = self.exchange();
log("Ok we have the promise");
// Wait for result of the async call
let result = ...
return Ok(result);
}
}
If necessary, I can provide a more complete example of the code.
Thanks
No, it is not possible. The browser does not allow for blocking. This is a limitation in the browser, not in Rust or wasm-bindgen, so there's nothing we can do about it.
So your only options are:
Make the function / method async.
Return an impl Future / Promise.
Use spawn_local:
impl Transport for TransportJS {
fn exchange(&self) {
spawn_local(async move {
// Call the javscript function exchange
let promise = self.exchange();
log("Ok we have the promise");
// Wait for result of the async call
let result = ...
});
}
}
Note that spawn_local does not block: it immediately returns () and then runs the Future in the background, it will not wait for the Future to finish.
Most helpful comment
No, it is not possible. The browser does not allow for blocking. This is a limitation in the browser, not in Rust or wasm-bindgen, so there's nothing we can do about it.
So your only options are:
Make the function / method
async.Return an
impl Future/Promise.Use
spawn_local:Note that
spawn_localdoes not block: it immediately returns()and then runs theFuturein the background, it will not wait for theFutureto finish.