Challenge - 5 Problems
Worker Threads Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple worker thread example
What will be printed to the console when this Node.js code runs?
Node.js
import { Worker, isMainThread, parentPort } from 'worker_threads'; if (isMainThread) { const worker = new Worker(new URL(import.meta.url)); worker.on('message', (msg) => console.log(msg)); } else { parentPort.postMessage('Hello from worker'); }
Attempts:
2 left
💡 Hint
Remember that the worker sends a message back to the main thread.
✗ Incorrect
The worker thread sends the string 'Hello from worker' to the main thread, which logs it.
❓ component_behavior
intermediate2:00remaining
Behavior of worker thread with data passed
What will be the output of this code snippet?
Node.js
import { Worker, isMainThread, parentPort, workerData } from 'worker_threads'; if (isMainThread) { const worker = new Worker(new URL(import.meta.url), { workerData: 5 }); worker.on('message', (msg) => console.log(msg)); } else { parentPort.postMessage(workerData * 2); }
Attempts:
2 left
💡 Hint
Check how workerData is used inside the worker thread.
✗ Incorrect
The main thread passes 5 as workerData. The worker multiplies it by 2 and sends 10 back.
📝 Syntax
advanced2:00remaining
Identify the syntax error in worker thread creation
Which option contains a syntax error that prevents the worker from starting?
Node.js
import { Worker, isMainThread } from 'worker_threads'; if (isMainThread) { const worker = new Worker('worker.js'); }
Attempts:
2 left
💡 Hint
Check how new URL() is used with relative paths in ES modules.
✗ Incorrect
new URL('worker.js') alone is invalid because it lacks a base URL, causing a TypeError.
🔧 Debug
advanced2:00remaining
Why does this worker thread code throw an error?
This code throws an error when run. What is the cause?
Node.js
import { Worker, isMainThread } from 'worker_threads'; if (isMainThread) { const worker = new Worker('./worker.js'); worker.on('message', (msg) => console.log(msg)); } else { parentPort.postMessage('Hi'); }
Attempts:
2 left
💡 Hint
Consider how worker threads are created in ES modules with relative paths.
✗ Incorrect
In ES modules, Worker constructor needs a URL object for relative paths, not a plain string.
❓ lifecycle
expert3:00remaining
Order of events in worker thread lifecycle
What is the correct order of these events when a worker thread is created and communicates back?
Attempts:
2 left
💡 Hint
Think about what happens first: creation, running, messaging, then receiving.
✗ Incorrect
First main thread creates the worker, then worker runs, sends message, and main thread receives it.