Congratulations, you made it to the end of the course! The weather station dashboard now runs in JavaScript. The stop button ends a poll, an old Ridge reading can’t overwrite a newer one, and the summaries run in workers that all exit before the total of 40 prints.
Here are three of the dashboard’s decisions, run once more. The worker module and the runWorker() helper come from the project unchanged:
worker.mjs
import { parentPort, workerData } from "node:worker_threads";
const total = workerData.reduce((sum, value) => sum + value, 0);
parentPort.postMessage({ total, count: workerData.length });
new URL() with import.meta.url finds the worker file next to the module, and new Promise() wraps the worker’s events in a promise. Once the worker starts, the promise settles only on exit, and it rejects if the worker emitted an error event or exited with a nonzero code. If the samples can’t be cloned, new Worker() throws instead, and the promise rejects at once:
run-worker.mjs
import { Worker } from "node:worker_threads";
const url = new URL("./worker.mjs", import.meta.url);
export function runWorker(samples) {
return new Promise((resolve, reject) => {
const worker = new Worker(url, { workerData: samples });
let result;
let failure;
worker.once("message", (message) => {
result = message;
});
worker.once("error", (error) => {
failure = error;
});
worker.once("exit", (code) => {
if (failure) reject(failure);
else if (code === 0 && result) resolve(result);
else reject(new Error(`Worker exit ${code}`));
});
});
}
The main module handles a stop requested before a poll begins, reserves one polling slot for two callers, and summarizes Ridge in a worker. stock counts the free slots. The empty poll() stands in for the cached poll that answers at once, though awaiting it still pauses execution:
import { setTimeout as sleep } from "node:timers/promises";
import { runWorker } from "./run-worker.mjs";
const controller = new AbortController();
controller.abort("operator stopped poll");
try {
await sleep(100, 8, { signal: controller.signal });
} catch (error) {
const signal = controller.signal;
if (!signal.aborted || error.cause !== signal.reason) throw error;
console.log("name:", error.name, "| cause:", error.cause);
}
let stock = 1;
async function poll() {}
async function reserve() {
if (stock === 0) return "sold out";
stock -= 1;
try {
await poll();
} catch (error) {
stock += 1;
throw error;
}
return "reserved";
}
console.log(await Promise.all([reserve(), reserve()]), stock);
console.log(await runWorker([8, 12, 10]));
The stop arrives as an AbortError carrying the operator’s reason, one caller gets the slot, which goes back if its poll fails, and the summary promise resolves only after its worker has exited: