GoogleChromeLabs / comlink

Comlink makes WebWorkers enjoyable.
Apache License 2.0
11.37k stars 390 forks source link

Class example not working #408

Open Dexus opened 4 years ago

Dexus commented 4 years ago

I try to run the example 03 with class in my project:

import * as Comlink from 'comlink';
import {
  Game
} from "./src/index.js"

console.log("start 1");
async function init() {
  console.log("start 2");
  const MyClass = Comlink.wrap(new Worker("worker.js"));
  console.log("start 3");
  console.log(MyClass);
  let worker = new MyClass();
  console.log("start 4");
  console.log(worker);
  let game = new Game(worker);
  console.log("start 5");
  console.log(game);
}
init().catch(console.trace);

worker.js:

import * as Comlink from 'comlink';
import("../../rust-src/pkg").then(wasm => {
  wasm.init();
  class MyClass {

    constructor() {
      console.log("Worker started");
    }

    request() {
      return wasm.request()
    }

    chacha20poly1305_decrypt(key, noce, str) {
      return wasm.chacha20poly1305_decrypt(key, noce, str)
    }

    chacha20poly1305_encrypt(key, noce, str) {
      return wasm.chacha20poly1305_encrypt(key, noce, str)
    }

    aes_encrypt(str) {
      return wasm.aes_encrypt(str)
    }
    hash(str) {
      return wasm.hash(str)
    }
  }

  Comlink.expose(MyClass);
});

But the await blocks the script as shown in the example. Is the example outdated or what is wrong?

surma commented 4 years ago

Can you put your example in a glitch or something? I wonder if it has something to do with the fact that you call expose async, but technically that should work 🤔

frnsys commented 3 years ago

I'm running into a similar problem, and I think it's related to WebAssembly. Everything works fine if I comment the line of code in my worker that calls a wasm function.