update web worker so its actually efficient

This commit is contained in:
Youwen Wu 2024-02-15 02:43:10 -08:00
parent 1dbc8de107
commit 9568b4b3f9
2 changed files with 8 additions and 8 deletions

View file

@ -8,13 +8,12 @@ export const loadDocument = (id: string): Promise<Document> => {
{ type: 'module' } { type: 'module' }
) )
worker.onmessage = (e: MessageEvent<{ [key: string]: Document }>) => { worker.onmessage = (e: MessageEvent<Document | undefined>) => {
const data = e.data const data = e.data
const doc: Document | undefined = data[id] if (!data) {
if (!doc) {
return reject(new Error('404')) return reject(new Error('404'))
} else { } else {
resolve(doc) resolve(data)
} }
worker.terminate() worker.terminate()
} }
@ -24,7 +23,7 @@ export const loadDocument = (id: string): Promise<Document> => {
worker.terminate() worker.terminate()
} }
worker.postMessage('LOAD') worker.postMessage(id)
} else { } else {
reject( reject(
new Error( new Error(
@ -34,6 +33,9 @@ export const loadDocument = (id: string): Promise<Document> => {
} }
}) })
} }
/**
* @deprecated This function doesn't improve efficiency and shouldn't be used
*/
export const loadAllDocuments = (): Promise<{ [key: string]: Document }> => { export const loadAllDocuments = (): Promise<{ [key: string]: Document }> => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (typeof Worker !== 'undefined') { if (typeof Worker !== 'undefined') {

View file

@ -1,7 +1,5 @@
import { documents } from '../data' import { documents } from '../data'
onmessage = (e) => { onmessage = (e) => {
if (e.data === 'LOAD') { typeof e.data === 'string' && postMessage(documents[e.data])
self.postMessage(documents)
}
} }