Built and running below.
A long job that reports progress, and can be cancelled
Streaming progress updates on the reply port until the final answer arrives, or cancelling work in flight. Delegating the reply to a third context by transferring the reply end.
The reply port does not have to carry one answer. This page asks a slow service for a job and keeps the reply port open. Progress arrives on it, ten per cent at a time. To cancel, this page says so on the same port and closes it. The service stops work, because nobody is waiting for the result any more.
Code
const { port1, port2 } = new MessageChannel();
service.postMessage({ job: "render" }, [port2]);
port1.onmessage = ({ data }) => data.done ? finish(data) : showProgress(data.percent);
// changed your mind
port1.postMessage({ cancel: true });
port1.close();
Step by step
What each press of Next does in this demo.
- Start a long job. The question goes out with a fresh reply port. Progress comes back on that port.
- Start a long job. The first job finished. Start a second one.
- Cancel it. This page tells the service to stop, on the reply port, and closes it. The service stops part-way.
Call a function on another origin and await the answer
Request/response RPC over ports — this is what Comlink and Hawser do underneath.
Twelve lines turn the reply pattern into await call("add", 2, 3). Each call makes a channel, sends one end with the question, and returns a promise that settles when the other end speaks. Errors come back as rejections. Three calls made at once come back to the right callers, even when the slow one finishes last, because each has its own channel.
Code
const call = (method, ...args) => new Promise((resolve, reject) => {
const { port1, port2 } = new MessageChannel();
port1.onmessage = ({ data }) => { "error" in data ? reject(new Error(data.error)) : resolve(data.result); port1.close(); };
service.postMessage({ method, args }, [port2]);
});
await call("add", 2, 3); // 5, computed on another origin
Step by step
What each press of Next does in this demo.
- await call("add", 2, 3). A question goes out with a reply port. The promise resolves with the answer.
- await call("divide", 1, 0). The service refuses. The promise rejects with its message.
- Three calls at once. Three questions, three wires. The slow one comes back last and still reaches the right caller.