Request-Response Patterns with PostMessage
What you'll learn: How to implement request-response messaging by correlating messages with unique IDs so workers can reply to specific requests.
The Challenge of Asynchronous Replies
When you send a message to a worker with postMessage, the worker might send multiple messages back over time. How do you know which response corresponds to which request? Without a correlation mechanism, you're just shouting into a room and hoping the right answer comes back.
The Solution: Message Correlation with IDs
The pattern is simple: attach a unique request ID to each message you send. When the worker responds, it includes that same ID. Your main thread can then match responses to their original requests using callbacks, promises, or async/await.
Think of it like a restaurant: You don't just yell your order into the kitchen. The server writes a ticket number on your order. When food comes out, they call that number so the right meal reaches the right table.
Implementation Strategy
- Generate unique IDs for each request (timestamps, counters, or UUIDs work)
- Store pending requests in a Map with ID as key, resolver callback as value
- Send messages with format like
{ id, type, data } - Worker echoes the ID back:
{ id, result } - Main thread looks up the ID and resolves the corresponding promise
This pattern transforms the fire-and-forget nature of postMessage into a clean async API where you can await worker responses just like fetch calls.
You can also use MessageChannel with dedicated ports per request, creating isolated request-response pairs without ID bookkeeping.
Key Takeaway: Correlating messages with unique IDs transforms postMessage into a structured request-response system, enabling promise-based APIs and preventing response mix-ups in concurrent worker communications.