Skip to content

Instantly share code, notes, and snippets.

@VehpuS
Created August 1, 2024 15:11
Show Gist options
  • Save VehpuS/c62e95e7d0420a9d30440c1eafab0f92 to your computer and use it in GitHub Desktop.
Save VehpuS/c62e95e7d0420a9d30440c1eafab0f92 to your computer and use it in GitHub Desktop.
Web pack enabled web workers
export const testFunction = () => {
return Array(1000).fill(2).map((n, i) => n * i).map((n, i) => n * i ** 2)
}
import { testFunction } from './testFunction';
onmessage = function (e: MessageEvent<{ args: Parameters<typeof testFunction> }>) {
const result = formatFeatures(...e.data.args);
postMessage(result);
};
import { testFunction } from './testFunction';
export async function testFunctionWebWorker(
...args: Parameters<typeof testFunction>
): Promise<ReturnType<typeof testFunction>> {
const worker = new Worker(new URL('./worker.ts', import.meta.url));
return new Promise<ReturnType<typeof testFunction>>((resolve, reject) => {
worker.onmessage = function (e: MessageEvent<ReturnType<typeof testFunction>>) {
resolve(e.data);
worker.terminate();
};
worker.onerror = function (e: ErrorEvent) {
reject(e);
worker.terminate();
};
worker.postMessage({ args });
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment