I'm writing a JS class, which calls wasmFunc
in the constructor and saves its result to this.val
. However, because wasmFunc
is from a WebAssembly file, an async function loadWasm
must be called before wasmFunc
is callable. So I'm trying to achieve something like this:
// index.js
async loadWasm() {
// load wasm file
}
export class MyClass {
constructor() {
await loadWasm(); // Cannot work
this.val = wasmFunc();
}
}
export const myObj = new MyClass();
Ideally, this file index.js
should export myObj
that is ready for use. However, await
cannot be used in the constructor.
Any solutions or thoughts?
Since a function can only do one of those things, a constructor function can't be async.
You can use a helper function:
// index.js
async loadWasm() {
// load wasm file
}
export class MyClass {
constructor(wasm) {
this.val = wasm;
}
}
async function myClassFactory() {
const wasm = await loadWasm();
const instance = new MyClass(wasm);
return instance;
}
You'll need to await
the result of calling myClassFactory()
.
You could also store a promise in the object you create:
// index.js
async loadWasm() {
// load wasm file
}
export class MyClass {
constructor() {
const wasmPromise = loadWasm();
this.val = wasmPromise;
}
async doSomethingWithValue() {
const wasm = await this.val;
console.log(wasm);
}
}