SqliteWorker: wait until worker is ready

This commit is contained in:
Alex Gleason 2023-11-15 17:09:30 -06:00
parent 87980bbba1
commit 71e8d26195
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
2 changed files with 18 additions and 3 deletions

View File

@ -1,17 +1,30 @@
class SqliteWorker {
#path: string;
#worker: Worker;
ready: Promise<void>;
constructor(path: string) {
this.#path = path;
this.#worker = new Worker(new URL('./sqlite.worker.ts', import.meta.url).href, { type: 'module' });
this.ready = new Promise<void>((resolve) => {
const handleEvent = (event: MessageEvent) => {
if (event.data[0] === 'ready') {
this.#worker.removeEventListener('message', handleEvent);
resolve();
}
};
this.#worker.addEventListener('message', handleEvent);
});
}
open(): Promise<void> {
async open(): Promise<void> {
await this.ready;
return this.#call(['open', [this.#path]]);
}
query(sql: string, params?: any): Promise<unknown[]> {
async query(sql: string, params?: any): Promise<unknown[]> {
await this.ready;
return this.#call(['query', [sql, params]]);
}

View File

@ -30,3 +30,5 @@ self.addEventListener('message', (event: MessageEvent<[string, Msg]>) => {
const result = call(msg);
self.postMessage([id, result]);
});
self.postMessage(['ready']);