0
0
Node.jsframework~20 mins

Receiving results from workers in Node.js - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Worker Thread Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What will this Node.js worker thread code output?

Consider this Node.js code using worker threads. What will be printed to the console?

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('Received:', msg));
  worker.postMessage('start');
} else {
  parentPort.on('message', (msg) => {
    if (msg === 'start') {
      parentPort.postMessage('done');
    }
  });
}
AReceived: done
BReceived: start
CNo output, program hangs
DThrows an error: parentPort is undefined
Attempts:
2 left
💡 Hint

Think about how the worker listens and sends messages back to the main thread.

state_output
intermediate
2:00remaining
What is the value of 'result' after worker completes?

In this Node.js code, what will be the value of result after the worker sends its message?

Node.js
import { Worker, isMainThread, parentPort } from 'worker_threads';

let result = null;

if (isMainThread) {
  const worker = new Worker(new URL(import.meta.url));
  worker.on('message', (msg) => {
    result = msg;
  });
  worker.postMessage('compute');

  setTimeout(() => {
    console.log('Result:', result);
  }, 100);
} else {
  parentPort.on('message', (msg) => {
    if (msg === 'compute') {
      parentPort.postMessage(42);
    }
  });
}
AThrows ReferenceError
BResult: null
CResult: 42
DResult: undefined
Attempts:
2 left
💡 Hint

The message event updates result before the timeout logs it.

📝 Syntax
advanced
2:00remaining
Which option causes a syntax error in worker message handling?

Which of these code snippets will cause a syntax error when used inside a Node.js worker thread?

AparentPort.on('message', msg => { if (msg === 'go') parentPort.postMessage('ok'); });
BparentPort.on('message', msg => { if (msg === 'go') { parentPort.postMessage('ok'); } });
CparentPort.on('message', function(msg) { if (msg === 'go') { parentPort.postMessage('ok'); } });
DparentPort.on('message', (msg) => { if msg === 'go' { parentPort.postMessage('ok'); } });
Attempts:
2 left
💡 Hint

Check the syntax of the if statement in each option.

🔧 Debug
advanced
2:00remaining
Why does this worker code throw 'TypeError: Cannot read property "postMessage" of null'?

Given this worker code snippet, why does it throw a TypeError?

Node.js
import { parentPort } from 'worker_threads';

parentPort.postMessage('hello');
ABecause parentPort is not imported correctly
BBecause the code runs in the main thread where parentPort is null
CBecause postMessage requires a callback function
DBecause 'hello' is not a valid message format
Attempts:
2 left
💡 Hint

Check where the code is executed: main thread or worker thread?

🧠 Conceptual
expert
3:00remaining
Which option correctly describes how results are received from multiple workers?

You spawn multiple worker threads in Node.js to perform tasks. How do you correctly receive and aggregate their results?

AListen to each worker's 'message' event and collect results in an array; use Promise.all to wait for all workers.
BCall worker.postMessage() with a callback to get the result synchronously.
CUse a shared global variable updated by all workers directly to store results.
DUse a single worker to handle all tasks sequentially to avoid message conflicts.
Attempts:
2 left
💡 Hint

Think about asynchronous message events and how to wait for all workers.