Last active
May 25, 2024 07:52
-
-
Save Megaemce/92f768c0686fc63666935d0a82f646d9 to your computer and use it in GitHub Desktop.
Using web workers with Promises in a React + TypeScript project
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default class ExampleClass { | |
private someArray: string[] = ["A","B","C","D"]; | |
// ... | |
/** | |
* Asynchronously executes a web worker example using an array of elements. | |
* Each element is processed by a web worker and the results are concatenated. | |
* | |
* @return {Promise<string>} A promise that resolves to a string containing the results of all web worker executions. | |
* @throws {Error} If there is an error in executing the web workers or if the worker returns an error. | |
*/ | |
public async webWorkersExample(): Promise<string> { | |
const results = this.someArray.map((element) => { | |
return new Promise<string>((resolve, reject) => { | |
const worker = new Worker(new URL("workers.ts", import.meta.url)); | |
worker.postMessage({ element: element }); | |
worker.onmessage = (e: MessageEvent) => { | |
worker.terminate(); | |
resolve(e.data.result); | |
}; | |
worker.onerror = (e) => { | |
worker.terminate(); | |
reject(new Error(`Worker error: ${e.message}`)); | |
}; | |
}); | |
}); | |
try { | |
const allResults = await Promise.all(results); | |
return allResults.join(); // this should return "A!B!C!D!" | |
} catch (error) { | |
console.error("Web workers error:", error); | |
throw error; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ... inside some React component where exampleClassObject is just an instance of ExampleClass | |
const [webWorkerResult, setWebWorkerResult] = useState(""); | |
useEffect(() => { | |
// IIFE. Making sure that result is a String not a Promise<string> | |
(async () => setWebWorkerResult(await exampleClassObject.webWorkersExample()))(); | |
}, [exampleClassObject]); | |
// now can use the webWorkerResult somewhere in the component | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
onmessage = function (e: MessageEvent): void { | |
const element = e.data.element; | |
const result = element + "!" // just as an example | |
postMessage({ result: result }); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment