0

Given the following (simplified) Rust code:

#[wasm_bindgen(js_name = MyClass)]
pub struct MyClassJs {
    my_struct: MyStruct,
}

#[wasm_bindgen(js_class = MyClass)]
impl MyClassJs {
    #[wasm_bindgen(constructor)]
    pub async fn new() -> Result<MyClassJs, JsValue> {
        // ...
    }
}

Compiled using wasm-pack, and this recommendation from the wasm-bindgen book:

// Note that a dynamic `import` statement here is required due to
// webpack/webpack#6615, but in theory `import { greet } from './pkg';`
// will work here one day as well!
const rust = import('./pkg');

rust
  .then(m => m.greet('World!'))
  .catch(console.error);

The previous statement makes me believe that doing any rust-wasm related calls are illegal until the Promise has resolved.

Which poses the question: which of these statements is true?

  1. Is it legal to call new MyClassJs() at any time (even before the Promise is resolved)?
  2. Is it legal to call new MyClassJs() only after the Promise is resolved (but anywhere, including outside the then callback?
  3. Is it legal to call new MyClassJs() only inside the then callback?

I have tried finding an answer using these resources, but have found them to not contain the answer to my question:

Edit: I am currently on webpack 4.

Erik Živković
  • 4,867
  • 2
  • 35
  • 53
  • How do you expect to ever access `MyClassJs` before the promise resolves? It doesn't exist in global scope, AFAIK. – Cerberus Dec 17 '21 at 10:12
  • @Cerberus rust-wasm / wasm-pack exports TypeScript definitions that are accessible without waiting for the module to load. I think the point I'm trying to make is that without webpack 5 wasm_bindgen(constructor) is kind of weird? – Erik Živković Dec 17 '21 at 10:20

0 Answers0