Building the Station Summary Dashboard
In this lesson, you build the station summary dashboard: one worker per station, and three lines to print. Ridge with 30 from three samples, Harbor with 10 from two, and a total of 40. Can JavaScript print these three lines, in this order, with every worker gone before the total?
The Python version is the reference your port has to match. summarize() adds up a station’s samples
and counts them. summarize_station() runs it in a process pool and puts the station’s id in front.
And main() gathers both stations, then prints each row and the grand total:
import asyncio
from concurrent.futures import ProcessPoolExecutor
STATIONS = [
{"id": "Ridge", "samples": [8, 12, 10]},
{"id": "Harbor", "samples": [4, 6]},
]
def summarize(samples):
return {"total": sum(samples), "count": len(samples)}
async def summarize_station(pool, station):
loop = asyncio.get_running_loop()
summary = await loop.run_in_executor(
pool, summarize, station["samples"]
)
return {"id": station["id"], **summary}
async def main():
with ProcessPoolExecutor() as pool:
rows = await asyncio.gather(
*(summarize_station(pool, s) for s in STATIONS)
)
for row in rows:
print(row)
total = sum(row["total"] for row in rows)
print("total", total)
if __name__ == "__main__":
asyncio.run(main())
In JavaScript, the work moves to worker.mjs, as before. It sums workerData with .reduce() and now
posts a count too, workerData.length, like Python’s len():