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.
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.
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 });
});
}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.