In the previous recipe, we saw how to create and send a message to a worker on a background thread. That's pretty great! Before Web Workers were introduced, it wasn't possible for JavaScript to work with anything but the main thread. However, it isn't very useful if we can't get any information back.
In this recipe, we'll see how to wait for, and send responses back from, a Web Worker.
This recipe assumes you already have a workspace that allows you to create and run ES modules in your browser. If you don't, please see the first two chapters.
- Open your command-line application and navigate to your workspace.
- Create a new folder named
05-02-send-messages-to-and-from-web-workers
. - Copy or create an
index.html
that loads and runs amain
function frommain.js
.
- Create a
main.js
with a function namedonMessage
that takes an argumentmessage
and logs out thetype
andindex
properties:
// main.js function onMessage(message) { const...