Skip to content
jshacks.dev
Async

Send messages to a worker and await replies

Send messages to a worker and await replies in Node.js: tag each request with an id and resolve its promise on the reply. Node.js 24.

1 min read
Summarize in AI

postMessage is fire and forget. To get an answer you can await, tag each request with an id and keep the matching resolver in a map.

rpc.mjsJavaScript
import { Worker, isMainThread, parentPort } from 'node:worker_threads';

if (isMainThread) {
  const worker = new Worker(new URL(import.meta.url));
  let nextId = 0;
  const pending = new Map();

  worker.on('message', ({ id, result }) => {
    pending.get(id)(result);
    pending.delete(id);
  });

  const call = (payload) =>
    new Promise((resolve) => {
      const id = nextId++;
      pending.set(id, resolve);
      worker.postMessage({ id, payload });
    });

  console.log(await call(2));
  console.log(await Promise.all([call(3), call(4)]));
  await worker.terminate();
} else {
  parentPort.on('message', ({ id, payload }) => {
    parentPort.postMessage({ id, result: payload * payload });
  });
}
Text
4
[ 9, 16 ]

Every reply carries the id of its request, so replies can come back in any order and still reach the right caller. Two calls in flight at once work because each has its own entry in pending. Add a second map entry for reject if the worker can fail, and send { id, error } for that case.

Terminate the worker when you are done, or it keeps the process alive. For many jobs a small pool of workers with this pattern beats starting a worker per call, because starting one is expensive.

Taggednode 24
Share

More snippets

Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read
Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.