fetchWorker: wait for the worker to be ready before using it

This commit is contained in:
Alex Gleason 2024-01-22 11:55:34 -06:00
parent dc6a6ccb5f
commit fc3934fa90
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
2 changed files with 15 additions and 7 deletions

View File

@ -4,21 +4,27 @@ import './handlers/abortsignal.ts';
import type { FetchWorker } from './fetch.worker.ts';
const _worker = Comlink.wrap<typeof FetchWorker>(
new Worker(
new URL('./fetch.worker.ts', import.meta.url),
{ type: 'module' },
),
);
const worker = new Worker(new URL('./fetch.worker.ts', import.meta.url), { type: 'module' });
const client = Comlink.wrap<typeof FetchWorker>(worker);
// Wait for the worker to be ready before we start using it.
const ready = new Promise<void>((resolve) => {
const handleEvent = () => {
self.removeEventListener('message', handleEvent);
resolve();
};
worker.addEventListener('message', handleEvent);
});
/**
* Fetch implementation with a Web Worker.
* Calling this performs the fetch in a separate CPU thread so it doesn't block the main thread.
*/
const fetchWorker: typeof fetch = async (...args) => {
await ready;
const [url, init] = serializeFetchArgs(args);
const { body, signal, ...rest } = init;
const result = await _worker.fetch(url, { ...rest, body: await prepareBodyForWorker(body) }, signal);
const result = await client.fetch(url, { ...rest, body: await prepareBodyForWorker(body) }, signal);
return new Response(...result);
};

View File

@ -24,3 +24,5 @@ export const FetchWorker = {
};
Comlink.expose(FetchWorker);
self.postMessage('ready');