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

Exposed function deadlocks if called too early #665

Open
EarlMilktea opened this issue Jul 21, 2024 · 1 comment
Open

Exposed function deadlocks if called too early #665

EarlMilktea opened this issue Jul 21, 2024 · 1 comment

Comments

@EarlMilktea
Copy link

Problem description

Wrapped function does not return when called before the worker is ready.

Minimum codes to reproduce

Deps.

  • comlink 4.4.1
  • esbuild 0.23.0 for bundling
// task.ts: Dummy task
// task.ts

// Dummy task
export async function dummyTask(time: number) {
  return new Promise((resolve) => {
    setTimeout(resolve, time);
  });
}
// worker.ts
import * as Comlink from "comlink";
import { dummyTask } from "./task.js";

// Wait for 500 ms
// Modeling long-running tasks (ex. WASM compilation)
await dummyTask(500);

Comlink.expose({
  dummy: () => {
    return 42;
  },
});
// index.ts
import * as Comlink from "comlink";
import { dummyTask } from "./task.js";

const url = new URL("./worker.js", import.meta.url);

const wrapper: Comlink.Remote<{
  dummy: () => number;
}> = Comlink.wrap(new Worker(url, { type: "module" }));

// Works without problem with this line
// await dummyTask(1000);

// Never returns
const x = await wrapper.dummy();

// Unreachable
console.log(x);
@eyyyyyyy3
Copy link

eyyyyyyy3 commented Oct 7, 2024

Yes I got the same problem. I can think of 2 workarounds:

  • At the end of the file (or the last expose instruction) the worker could postMessage that he is done. The caller could then wait for this signal.
  • Be sure that you workers first define/declare and expose before any code is actually run.
    The first idea could be built into comlink with some function like initialized or finalExportwhich the worker/exposer would call after everything has been exposed.

Edit: This problem is already known #635 #635 (comment)

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

No branches or pull requests

2 participants