Listening for messages on the main script

We can listen to what a worker sent to the main script with the onmessage event. This is how it'll look:

// script.jsconst awesomeworker = new Worker('myworker.js');awesomeworker.addEventListener('message', e => {    console.log(e.data); // data sent by worker});

Here, our script is listening for messages sent by the worker. Every time a worker sends a message (which we'll see how to do in a minute, in the Sending messages from the main script section), the previous event is triggered and we console the data.

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.