Bird
0
0

You want to create a worker thread that performs a CPU-heavy calculation and sends the result back. Which approach correctly creates the worker and handles the result asynchronously?

hard📝 Application Q15 of 15
Node.js - Worker Threads
You want to create a worker thread that performs a CPU-heavy calculation and sends the result back. Which approach correctly creates the worker and handles the result asynchronously?
AUse <code>new Worker()</code> without arguments and call <code>worker.send()</code> to communicate
BUse <code>new Worker('./calc.js')</code> with <code>worker.on('message', callback)</code> and send data via <code>worker.postMessage()</code>
CUse <code>require('worker_threads').run()</code> to start the worker and get a promise
DCreate a child process with <code>child_process.fork()</code> and communicate with <code>worker.postMessage()</code>
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct Worker creation and communication

    Creating a worker with new Worker('./calc.js') and using worker.on('message') plus worker.postMessage() is the standard pattern.
  2. Step 2: Eliminate incorrect options

    Use new Worker() without arguments and call worker.send() to communicate is invalid because Worker requires a filename or code. Use require('worker_threads').run() to start the worker and get a promise is incorrect; no run() method exists. Create a child process with child_process.fork() and communicate with worker.postMessage() uses child_process, not worker_threads, and postMessage is not valid on child processes.
  3. Final Answer:

    Use new Worker('./calc.js') with worker.on('message', callback) and send data via worker.postMessage() -> Option B
  4. Quick Check:

    Worker with filename + message events = A [OK]
Quick Trick: Use new Worker(filename) and message events for communication [OK]
Common Mistakes:
  • Trying to create Worker without filename
  • Confusing child_process with worker_threads
  • Using non-existent Worker methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes