Bird
Raised Fist0
Node.jsframework~20 mins

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

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

Practice

(1/5)
1. In Node.js, how do you receive results from a worker thread?
easy
A. By using console.log inside the worker
B. By calling worker.getResult() method
C. By listening to the message event on the worker
D. By reading from a shared file

Solution

  1. Step 1: Understand worker communication

    Workers send results back to the main thread using messages.
  2. Step 2: Use the correct event listener

    The main thread listens to the message event on the worker to receive data.
  3. Final Answer:

    By listening to the message event on the worker -> Option C
  4. Quick Check:

    message event = D [OK]
Hint: Remember: workers send data via 'message' events [OK]
Common Mistakes:
  • Trying to call a non-existent method like getResult()
  • Expecting console.log output to be received
  • Reading results from files instead of messages
2. Which of the following is the correct syntax to listen for messages from a worker in Node.js?
easy
A. worker.on('message', (result) => { console.log(result); });
B. worker.listen('message', (result) => { console.log(result); });
C. worker.addEventListener('message', (result) => { console.log(result); });
D. worker.receive('message', (result) => { console.log(result); });

Solution

  1. Step 1: Recall Node.js worker event syntax

    Node.js workers use the on method to listen for events.
  2. Step 2: Identify the correct event and method

    The event to receive data is message, and the syntax is worker.on('message', callback).
  3. Final Answer:

    worker.on('message', (result) => { console.log(result); }); -> Option A
  4. Quick Check:

    worker.on('message') = A [OK]
Hint: Use worker.on('message', callback) to get results [OK]
Common Mistakes:
  • Using non-existent methods like listen or receive
  • Confusing browser event syntax with Node.js
  • Using addEventListener which is not in Node.js workers
3. What will be logged to the console when this Node.js worker code runs?
const { Worker } = require('worker_threads');
const worker = new Worker(`
  const { parentPort } = require('worker_threads');
  parentPort.postMessage('Hello from worker');
`, { eval: true });
worker.on('message', (msg) => console.log(msg));
medium
A. undefined
B. No output
C. Error: parentPort is not defined
D. Hello from worker

Solution

  1. Step 1: Understand worker code execution

    The worker sends a message 'Hello from worker' using parentPort.postMessage.
  2. Step 2: Check main thread message listener

    The main thread listens to the message event and logs the received message.
  3. Final Answer:

    Hello from worker -> Option D
  4. Quick Check:

    postMessage sends 'Hello from worker' = B [OK]
Hint: postMessage sends data, main thread logs it on 'message' event [OK]
Common Mistakes:
  • Expecting no output because of missing event listener
  • Confusing parentPort usage causing errors
  • Assuming worker code runs in main thread
4. Identify the error in this Node.js worker communication code:
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js');
worker.on('message', (data) => {
  console.log('Received:', data);
});
parentPort.postMessage('start');
medium
A. Cannot call postMessage on the worker instance
B. postMessage should be called on parentPort inside worker, not on worker instance
C. Missing error event listener on worker
D. The worker file path is incorrect

Solution

  1. Step 1: Understand where postMessage is called

    In Node.js, postMessage is called on parentPort inside the worker, not on the worker instance in main thread.
  2. Step 2: Identify correct communication method

    The main thread uses worker.postMessage() to send messages to the worker, but inside the worker, parentPort.postMessage() sends messages back.
  3. Final Answer:

    postMessage should be called on parentPort inside worker, not on worker instance -> Option B
  4. Quick Check:

    postMessage usage inside worker = C [OK]
Hint: postMessage on worker sends to worker; inside worker use parentPort.postMessage [OK]
Common Mistakes:
  • Confusing where to call postMessage
  • Ignoring error event listeners
  • Assuming worker file path is wrong without evidence
5. You want to receive multiple results from a worker that sends messages repeatedly. Which approach correctly handles this in Node.js?
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js');
// What should you do here to receive all messages?
hard
A. Use worker.on('message', (msg) => { console.log(msg); }); to listen continuously
B. Call worker.once('message', (msg) => { console.log(msg); }); to listen once
C. Use a loop to call worker.postMessage repeatedly
D. Use setTimeout to poll worker for messages

Solution

  1. Step 1: Understand event listeners for multiple messages

    Using worker.on('message') listens continuously for all messages sent by the worker.
  2. Step 2: Compare with other options

    once listens only once, loops or polling are unnecessary and inefficient for receiving messages.
  3. Final Answer:

    Use worker.on('message', (msg) => { console.log(msg); }); to listen continuously -> Option A
  4. Quick Check:

    Continuous message listening = A [OK]
Hint: Use worker.on('message') for all messages, not once or polling [OK]
Common Mistakes:
  • Using once instead of on for multiple messages
  • Trying to poll worker instead of event listening
  • Confusing sending messages with receiving them