How to do it...

  1. Open your command-line application and navigate to your workspace.
  2. Create a new folder named 05-03-send-data-to-and-from-web-workers.
  3. Copy or create an index.html that loads and runs a main function from main.js.
  4. Create a main.js with a function named onMessage that takes an argument message and logs out the type and index properties:
// main.js 
function onMessage(message) { 
  const { result, type } = message.data; 
  console.log('Result for operation (%s): (%s)', type, result); 
}  
  1. Create a main function that creates a worker, sets the onMessage property, creates an array of random numbers, and posts two messages to the worker, one to sum some of the numbers and another to average them:
export function main() { const worker ...

Get ECMAScript Cookbook 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.