Skip to content

Instantly share code, notes, and snippets.

@Megaemce
Last active May 25, 2024 07:52
Show Gist options
  • Save Megaemce/92f768c0686fc63666935d0a82f646d9 to your computer and use it in GitHub Desktop.
Save Megaemce/92f768c0686fc63666935d0a82f646d9 to your computer and use it in GitHub Desktop.
Using web workers with Promises in a React + TypeScript project
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;
}
}
}
// ... 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
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