Sending messages from the worker script

Similar to the main script, postMessage is used in the worker script to communicate to the main script. Let us see how to post the previous result to the main script:

// myworker.jsaddEventListener('message', e => {    if(e.data.task == "add") {        const res = e.data.nums.reduce((sum, num) => sum+num, 0);        postMessage({task: "add", result: res}); // self.postMessage will also work    }});

Here, just like in the preceding code, we're reducing the array value to the sum, and then actually sending back whatever we did to the main UI script with the postMessage function. The passed object can be received by calling the script inside its own listening method.

script.js would look like the following:

// script.js

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.