Web Workers let your program do many things at once without slowing down the main part. This helps keep your app smooth and fast.
Web Workers for parallel processing in Deno
const worker = new Worker(new URL('./worker.ts', import.meta.url).href, { type: 'module' }); worker.postMessage(data); worker.onmessage = (event) => { console.log('Result from worker:', event.data); }; worker.onerror = (event) => { console.error('Worker error:', event.message); };
Use new Worker() with a module script URL in Deno.
Communicate with the worker using postMessage and listen with onmessage.
const worker = new Worker(new URL('./worker.ts', import.meta.url).href, { type: 'module' }); worker.postMessage({ number: 10 }); worker.onmessage = (e) => console.log(e.data);
worker.onmessage = (event) => {
console.log('Worker says:', event.data);
};worker.onerror = (event) => {
console.error('Error in worker:', event.message);
};This example creates a worker that calculates the square of a number. The main script sends the number 5, and the worker sends back 25. The main script then prints the result and stops the worker.
// main.ts const worker = new Worker(new URL('./worker.ts', import.meta.url).href, { type: 'module' }); worker.postMessage(5); worker.onmessage = (event) => { console.log(`Square of 5 is ${event.data}`); worker.terminate(); }; worker.onerror = (event) => { console.error('Worker error:', event.message); }; // worker.ts self.onmessage = (event) => { const num = event.data; const result = num * num; self.postMessage(result); };
Workers run in a separate thread, so they cannot access the main thread's variables directly.
Always terminate workers when done to free resources.
Use message passing to send data back and forth between main and worker.
Web Workers help run tasks in parallel without freezing the app.
Use postMessage and onmessage to communicate.
Remember to handle errors and terminate workers when finished.
Practice
Solution
Step 1: Understand Web Workers role
Web Workers allow running scripts in background threads separate from the main thread.Step 2: Identify the benefit
This prevents the main thread from freezing during heavy tasks, enabling parallel processing.Final Answer:
To run tasks in parallel without blocking the main thread -> Option BQuick Check:
Web Workers = Parallel tasks without blocking [OK]
- Thinking Web Workers handle HTTP or database tasks directly
- Confusing Web Workers with main thread code
- Assuming Web Workers manage permissions
Solution
Step 1: Recall message sending method
In Web Workers, the method to send data to the worker ispostMessage.Step 2: Match correct syntax
Among the options, onlyworker.postMessage('Hello')is valid and recognized.Final Answer:
worker.postMessage('Hello') -> Option AQuick Check:
Send message = postMessage [OK]
- Using send() instead of postMessage()
- Confusing emit() with event emitters
- Trying to call message() which doesn't exist
const worker = new Worker(new URL('./worker.ts', import.meta.url).href, { type: 'module' });
worker.onmessage = (e) => console.log('Result:', e.data);
worker.postMessage(5);And the worker.ts contains:
self.onmessage = (e) => {
const num = e.data;
self.postMessage(num * 2);
};What will be printed in the console?
Solution
Step 1: Understand message flow
The main thread sends 5 to the worker. The worker receives it asnum.Step 2: Calculate worker response
The worker multiplies 5 by 2 and sends back 10. The main thread logs 'Result: 10'.Final Answer:
Result: 10 -> Option AQuick Check:
5 * 2 = 10 output [OK]
- Assuming worker returns original number
- Confusing onmessage event usage
- Expecting error due to URL usage
const worker = new Worker('./worker.ts', { type: 'module' });
worker.postMessage('start');
worker.onmessage = (e) => console.log(e.data);
worker.terminate();Solution
Step 1: Analyze termination timing
The worker is terminated right after sending the message, likely before it can respond.Step 2: Effect on message reception
Because of immediate termination, the onmessage handler never receives data.Final Answer:
Worker is terminated immediately, so no message is received -> Option CQuick Check:
Terminate too soon = no response [OK]
- Thinking postMessage order causes error
- Ignoring worker path resolution rules
- Forgetting to handle errors but not critical here
Solution
Step 1: Understand parallel processing strategy
Splitting the array into parts and assigning each to a separate worker allows true parallelism.Step 2: Collect and combine results
Each worker returns partial results; the main thread combines them for the final output.Final Answer:
Create multiple workers, send each a slice of the array, collect partial results, then combine them -> Option DQuick Check:
Split work + combine results = efficient parallelism [OK]
- Sending full array multiple times wastes resources
- Using one worker loses parallel benefit
- Ignoring main thread processing slows app
Ready to prove it?
Pass the test and this pattern moves unknown
