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

Created on 29 Apr 2020  路  1Comment  路  Source: rustwasm/wasm-bindgen

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

question

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:

  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.

>All comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

poccariswet picture poccariswet  路  3Comments

MarcAntoine-Arnaud picture MarcAntoine-Arnaud  路  3Comments

alexcrichton picture alexcrichton  路  3Comments

shepmaster picture shepmaster  路  3Comments

hunterlester picture hunterlester  路  4Comments