Consider this Deno Web Worker code that sends a message to the worker and receives a response. What will be printed in the main thread console?
const worker = new Worker(new URL('./worker.ts', import.meta.url).href, { type: 'module' }); worker.onmessage = (e) => { console.log('Main thread received:', e.data); worker.terminate(); }; worker.postMessage('hello'); // worker.ts content: // self.onmessage = (e) => { // self.postMessage(e.data.toUpperCase()); // };
Remember that the worker converts the message to uppercase before sending it back.
The worker receives 'hello', converts it to uppercase 'HELLO', and sends it back. The main thread logs this result.
In Deno, you want to create a Web Worker using inline code (a Blob URL). Which option correctly creates the worker?
Creating a Blob URL requires using URL.createObjectURL with a Blob object.
Option C correctly creates a Blob with JavaScript code and then creates a URL for the worker. Other options misuse Blob or URL constructors.
This code tries to create a worker but throws an error. What is the cause?
const worker = new Worker('./worker.ts', { type: 'module' }); worker.postMessage('test'); // Error: Uncaught TypeError: Failed to construct 'Worker': Script at './worker.ts' cannot be accessed from origin 'null'.
Check how Deno resolves worker script URLs.
Deno requires an absolute URL for the worker script, often using new URL('./worker.ts', import.meta.url).href. Relative paths cause origin errors.
A main thread sends numbers to a worker that sums them. After sending 3 numbers, what is the final 'count' value received?
// main.ts const worker = new Worker(new URL('./sumWorker.ts', import.meta.url).href, { type: 'module' }); let count = 0; worker.onmessage = (e) => { count = e.data; }; worker.postMessage(5); worker.postMessage(10); worker.postMessage(3); // sumWorker.ts let total = 0; self.onmessage = (e) => { total += e.data; self.postMessage(total); };
The worker adds each number to total and sends the updated sum back.
The worker sums 5 + 10 + 3 = 18 and sends this back after each message. The main thread's 'count' ends at 18.
Choose the correct statement about Web Workers in Deno.
Think about how modern JavaScript modules work in workers.
Deno Web Workers run in separate threads and support ES modules with 'type: module'. They do not share global state and support async/await.
