Worker messages: clone data and correlate requests
Quick answer
Worker messages are delivered asynchronously. A small message protocol can associate a response with the request that produced it.
How it works
Use worker.postMessage(value) and handle the receiving message event. Ordinary cloneable objects are copied using structured serialization; functions are not cloneable. Include a request ID and a validated payload, and return an ID with the response. The sender does not obtain the response as the return value of postMessage. Handle errors and avoid trusting arbitrary payload shape.
Local examples
Run in a fresh browser document with local synthetic data. Actual ByteMind editor support is unverified.
(async () => {const url=URL.createObjectURL(new Blob(['self.onmessage=e=>self.postMessage({id:e.data.id,total:e.data.n*2});'],{type:"text/javascript"}));let w;try{w=new Worker(url);const result=new Promise((resolve,reject)=>{w.onmessage=e=>resolve(e.data);w.onerror=e=>reject(new Error(e.message));});w.postMessage({id:7,n:5});console.log(JSON.stringify(await result));}finally{w?.terminate();URL.revokeObjectURL(url);}})()Expected console output:
{"id":7,"total":10}The echoed ID correlates the answer with its request.
Run in a fresh browser document with local synthetic data. Actual ByteMind editor support is unverified.
(async () => {const url=URL.createObjectURL(new Blob(['self.onmessage=e=>self.postMessage(e.data.n);'],{type:"text/javascript"}));let w;try{w=new Worker(url);const result=new Promise((ok,no)=>{w.onmessage=e=>ok(e.data);w.onerror=e=>no(new Error(e.message));});const x={n:3};w.postMessage(x);x.n=8;console.log(await result);}finally{w?.terminate();URL.revokeObjectURL(url);}})()Expected console output:
3The ordinary object was cloned when sent; the later mutation stays local.
Common mistakes
Do not use a single global result slot for unrelated simultaneous jobs. Do not send functions or assume later mutations reach a previously sent object.
Practice
Send two bounded requests with different IDs and collect a result record by ID rather than by completion position.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Worker messages: clone data and correlate requests — Knowledge Check
Apply the concept and reason about local example output.
What does worker.postMessage return instead of the future response?
Why include an ID in a worker request and response?
What happens to a normal cloneable object when it is posted?
What is the expected console output of Worker messages: clone data and correlate requests example 1?
(async () => {const url=URL.createObjectURL(new Blob(['self.onmessage=e=>self.postMessage({id:e.data.id,total:e.data.n*2});'],{type:"text/javascript"}));let w;try{w=new Worker(url);const result=new Promise((resolve,reject)=>{w.onmessage=e=>resolve(e.data);w.onerror=e=>reject(new Error(e.message));});w.postMessage({id:7,n:5});console.log(JSON.stringify(await result));}finally{w?.terminate();URL.revokeObjectURL(url);}})()What is the expected console output of Worker messages: clone data and correlate requests example 2?
(async () => {const url=URL.createObjectURL(new Blob(['self.onmessage=e=>self.postMessage(e.data.n);'],{type:"text/javascript"}));let w;try{w=new Worker(url);const result=new Promise((ok,no)=>{w.onmessage=e=>ok(e.data);w.onerror=e=>no(new Error(e.message));});const x={n:3};w.postMessage(x);x.n=8;console.log(await result);}finally{w?.terminate();URL.revokeObjectURL(url);}})()