From fc3934fa90e119a52243f87d34661463ccb3e21d Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 22 Jan 2024 11:55:34 -0600 Subject: [PATCH] fetchWorker: wait for the worker to be ready before using it --- src/workers/fetch.ts | 20 +++++++++++++------- src/workers/fetch.worker.ts | 2 ++ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/workers/fetch.ts b/src/workers/fetch.ts index 3246e78..510d806 100644 --- a/src/workers/fetch.ts +++ b/src/workers/fetch.ts @@ -4,21 +4,27 @@ import './handlers/abortsignal.ts'; import type { FetchWorker } from './fetch.worker.ts'; -const _worker = Comlink.wrap( - 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(worker); + +// Wait for the worker to be ready before we start using it. +const ready = new Promise((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); }; diff --git a/src/workers/fetch.worker.ts b/src/workers/fetch.worker.ts index 8a2c0b1..8e79465 100644 --- a/src/workers/fetch.worker.ts +++ b/src/workers/fetch.worker.ts @@ -24,3 +24,5 @@ export const FetchWorker = { }; Comlink.expose(FetchWorker); + +self.postMessage('ready');