Course contentsShow
← JavaScript
Lesson 2150 of 2,72345. Workers and ConcurrencyFree lesson

Listening for Messages

Understand how to set up message event listeners in both the main thread and worker to receive data from each other.

Listening for Messages

You'll learn how to set up message event listeners so your main thread and worker can actually receive the data they send to each other.

The Two-Way Radio Analogy

Sending messages with postMessage is like speaking into a walkie-talkie—but someone has to be listening on the other end. Both the main thread and the worker need event listeners that "tune in" to incoming messages. Without these listeners, messages are broadcast into the void and lost forever.

Setting Up Listeners in the Main Thread

When your worker sends data back, the main thread needs to listen for it using the message event:

const worker = new Worker('worker.js');

// Listen for messages FROM the worker
worker.addEventListener('message', (event) => {
  console.log('Main thread received:', event.data);
});

// Send a message TO the worker
worker.postMessage({ task: 'calculate', value: 42 });

The event.data property contains whatever the worker sent via postMessage.

Setting Up Listeners in the Worker

Inside worker.js, you listen using the global self object (or just use the global message event):

// worker.js
self.addEventListener('message', (event) => {
  console.log('Worker received:', event.data);
  
  // Process and reply
  const result = event.data.value * 2;
  self.postMessage({ result });
});

Bidirectional Communication

Each side can both send and listen. The main thread sends instructions, the worker listens, processes, then sends results back while the main thread listens for those results. It's a continuous conversation, not a one-way broadcast.

Key Takeaway: Use addEventListener('message', ...) on both the worker object (main thread) and self (inside worker) to receive data sent via postMessage—without listeners, messages are silently dropped.