cotyC
Denoβ€’2y agoβ€’
3 replies
coty

How to detect if executing on main thread vs worker

function main() {
  // create worker from this same file
  const worker = new Worker(import.meta.resolve("./mod.ts"), {
      name: "hello-worker",
      type: "module",
  });
  worker.onmessage = (e: MessageEvent<{ message: string }>) => {
      console.log(e.data.message);
  };
  worker.postMessage({
      message: "hello",
  });
}

if (import.meta.main) {
    if (self.window) {
        main();
    } else {
        const worker = self as unknown as Worker & { name?: string };
        worker.onmessage = (e: MessageEvent<{ message: string }>) => {
            worker.postMessage({
                message: `${e.data.message} from ${worker.name}`,
            });
            self.close();
        };
    }
}

I put everything in one file to make it easier to show, but is checking for self.window the preferred way? or is there some value in Deno context?

Bonus question, how can you properly type self when in a worker? That type casting is neither pretty nor accurate
Was this page helpful?