Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[wasm-bindgen-futures] Is it possible to block an async javascript call in rust ? #2111

Closed
rllola opened this issue Apr 29, 2020 · 1 comment
Labels

Comments

@rllola
Copy link

rllola commented Apr 29, 2020

Summary

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

@Pauan
Copy link
Contributor

Pauan commented Apr 29, 2020

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:

  1. Make the function / method async.

  2. Return an impl Future / Promise.

  3. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants