@samitouri / QOSami-HFS / commits / 4cd112d1

better code: leverage debounceAsync

Massimo Melina committed Sep 26, 2023 at 15:27 UTC 4cd112d15e09e94d9087bf02e38f277b468529c5
2 files changed +6 -12
src/debounceAsync.ts
+1
@@ -21,6 +21,7 @@ export function debounceAsync<Cancelable extends boolean = false, A extends unkn
21 return Object.assign(interceptingWrapper, {
22 clearRetain: () => last = undefined,
23 flush: () => runningCallback ?? exec(),
24 + isWorking: () => runningCallback,
25 ...cancelable && {
26 cancel() {
27 waitingSince = 0
src/watchLoad.ts
+5 -12
@@ -15,22 +15,15 @@ export function watchLoad(path:string, parser:(data:any)=>void|Promise<void>, {
15 let watcher: FSWatcher | undefined
16 const debounced = debounceAsync(load, 500, { maxWait: 1000 })
17 let retry: NodeJS.Timeout
18 - let saving: Promise<unknown> | undefined
18 let last: string | undefined
19 install(true)
21 - return {
22 - unwatch: uninstall,
23 - save: (data: string) => Promise.resolve(saving).catch(() => {}).then(() => { // wait in case another is ongoing
24 - console.debug('writing', path)
25 - return saving = fs.writeFile(path, data, 'utf8').finally(() => // save but also keep track of the current operation
26 - saving = undefined)
27 - }) // clear
28 - }
20 + const save = debounceAsync((data: string) => fs.writeFile(path, data, 'utf8'))
21 + return { unwatch, save }
22
23 function install(first=false) {
24 try {
25 watcher = watch(path, () => {
33 - if (!saving)
26 + if (!save.isWorking())
27 debounced().then()
28 })
29 debounced().catch(x=>x)
@@ -44,7 +37,7 @@ export function watchLoad(path:string, parser:(data:any)=>void|Promise<void>, {
37 }
38 }
39
47 - function uninstall() {
40 + function unwatch() {
41 watcher?.close()
42 clearTimeout(retry)
43 watcher = undefined
@@ -63,7 +56,7 @@ export function watchLoad(path:string, parser:(data:any)=>void|Promise<void>, {
56 return
57 last = text
58 console.debug('loaded', path)
66 - uninstall(); install() // reinstall, as the original file could have been renamed. We watch by the name.
59 + unwatch(); install() // reinstall, as the original file could have been renamed. We watch by the name.
60 await parser(text)
61 }
62 finally {