Skip to content

Commit

Permalink
fix: race condition on web worker
Browse files Browse the repository at this point in the history
  • Loading branch information
cecilia-sanare committed Jun 27, 2024
1 parent 056772d commit 4e1eaf8
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
5 changes: 2 additions & 3 deletions src/pages/apps/SearchPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,8 @@ export const Component: FC = () => {
setLoading(true);

SearchService.query(search)
.then((apps) => {
setFilteredApps(apps);
})
.then((apps) => setFilteredApps(apps))
.catch(() => console.log('debounced...'))
.finally(() => {
setLoading(false);
});
Expand Down
22 changes: 18 additions & 4 deletions src/service/search.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import type { App } from '@/types';
import SearchWorker from '@/workers/search.worker?worker';

const worker: Worker = new SearchWorker();
let previousWorker: Worker;

export class SearchService {
static async query(value: string): Promise<App[]> {
return new Promise((resolve) => {
worker.addEventListener(
if (previousWorker) {
previousWorker.terminate();
}

previousWorker = new SearchWorker();

return new Promise((resolve, reject) => {
previousWorker.addEventListener(
'message',
(event) => {
resolve(event.data);
Expand All @@ -16,7 +22,15 @@ export class SearchService {
}
);

worker.postMessage(value);
// There's almost certainly a better way of doing this, but I don't have time to figure it out atm.
((terminate) => {
previousWorker.terminate = function () {
terminate.apply(previousWorker);
reject('Interupting due to new call');
};
})(previousWorker.terminate);

previousWorker.postMessage(value);
});
}
}

0 comments on commit 4e1eaf8

Please sign in to comment.