Receiving data from a worker
Learn to catch messages from the worker with onmessage.
Receiving data with onmessage
To catch messages from the worker, assign a function to worker.onmessage on the main side. When the worker calls postMessage, this function receives a MessageEvent.
worker.onmessage = function(event) {
console.log(event.data);
};The event's data property carries the payload sent by the worker. event.target points to the worker instance. If several messages arrive, the function runs once for each.
Catching errors with onerror
When an error occurs in the worker, worker.onerror fires. This listener receives an event with the error message, file name and line number.
worker.onerror = function(event) {
console.error(event.message);
};Listening for the error event stops the worker from failing silently. The safest path is still to restart the worker and report the error to the user. Logging makes the source of the problem easier to find.
Exercise Log data received from the worker
Assign a function to worker.onmessage. The function takes an event parameter and logs event.data with console.log.
Show example solution
worker.onmessage = function(event) {
console.log(event.data);
};
Test yourself
-
MessageEvent parts
- event.data
- the payload
- event.target
- the worker instance
- onmessage
- event listener
- postMessage
- sends a message
-
Log the data
worker.onmessage = function(event) { console.log(event.____); };Show answer
worker.onmessage = function(event) { console.log(event.data); }; -
Which one is used to receive data from a worker?
- worker.send()
- worker.getData()
- worker.fetch()
- worker.onmessage
Show answer
worker.onmessage — Correct! worker.onmessage catches incoming messages.