better code: void seems a clearer way to dismiss a promise

Massimo Melina committed Mar 27, 2024 at 10:02 UTC 82fc0e02ef33bdd3a1c18702a8d678ee2c898f72
20 files changed +33 -33
admin/src/AccountForm.ts
+1 -1
@@ -97,7 +97,7 @@ export default function AccountForm({ account, done, groups, addToBar, reload }:
97 if (password)
98 try { await apiNewPassword(values.username, password) }
99 catch(e) {
100 - apiCall('del_account', { username: values.username }).then() // best effort, don't wait
100 + void apiCall('del_account', { username: values.username }) // best effort, don't wait
101 throw e
102 }
103 done(got?.username)
admin/src/ConfigFilePage.ts
+1 -1
@@ -50,7 +50,7 @@ export default function ConfigFilePage() {
50 onValueChange: setText,
51 onKeyDown(ev) {
52 if (['s','Enter'].includes(isCtrlKey(ev) as any)) {
53 - save().then()
53 + void save()
54 ev.preventDefault()
55 }
56 },
admin/src/CustomHtmlPage.ts
+1 -1
@@ -57,7 +57,7 @@ export default function CustomHtmlPage() {
57 },
58 onKeyDown(ev) {
59 if (['s','Enter'].includes(isCtrlKey(ev) as any)) {
60 - save().then()
60 + void save()
61 ev.preventDefault()
62 }
63 },
admin/src/InternetPage.ts
+2 -2
@@ -40,7 +40,7 @@ export default function InternetPage() {
40 const verifyAgain = useRequestRender()
41 useEffect(() => {
42 if (verifyAgain.state) // skip first
43 - verify(true).then()
43 + void verify(true)
44 }, [verifyAgain.state])
45 return h(Flex, { vert: true, gap: '2em', maxWidth: '40em' },
46 h(Alert, { severity: 'info' }, "This page makes sure your site is working correctly on the Internet"),
@@ -248,7 +248,7 @@ export default function InternetPage() {
248 size: 'small',
249 variant: 'outlined',
250 'aria-label': "Change address",
251 - onClick: () => void(changeBaseUrl().then(config.reload))
251 + onClick: () => void changeBaseUrl().then(config.reload)
252 }, "Change"),
253 domain && h(Btn, {
254 size: 'small',
admin/src/OptionsPage.ts
+2 -2
@@ -43,7 +43,7 @@ export default function OptionsPage() {
43 const statusApi = useApiEx(data && 'get_status')
44 const status = statusApi.data
45 const reloadStatus = exposedReloadStatus = statusApi.reload
46 - useEffect(() => void(reloadStatus()), [data]) //eslint-disable-line
46 + useEffect(() => void reloadStatus(), [data]) //eslint-disable-line
47 useEffect(() => () => exposedReloadStatus = undefined, []) // clear on unmount
48 const sm = useBreakpoint('sm')
49
@@ -104,7 +104,7 @@ export default function OptionsPage() {
104 { k: 'https_port', comp: PortField, md: 4, label: "HTTPS port", status: status?.https||true, suggestedPort: 443,
105 onChange(v: number) {
106 if (v >= 0 && !httpsEnabled && !values.cert)
107 - suggestMakingCert().then()
107 + void suggestMakingCert()
108 return v
109 }
110 },
frontend/src/BrowseFiles.ts
+1 -1
@@ -288,7 +288,7 @@ export const EntryDetails = memo(({ entry, midnight }: { entry: DirEntry, midnig
288 'aria-hidden': true,
289 onClick() { // mobile has no hover
290 if (shortTs)
291 - alertDialog(t`Full timestamp:` + "\n" + time.toLocaleString()).then()
291 + void alertDialog(t`Full timestamp:` + "\n" + time.toLocaleString())
292 }
293 }, time.toLocaleString(navigator.language, {
294 ...!shortTs || !today ? { year: shortTs ? dd : 'numeric', month: dd, day: dd } : null,
frontend/src/login.ts
+1 -1
@@ -137,7 +137,7 @@ export function useAuthorized() {
137 if (!loginRequired)
138 return closeLoginDialog?.()
139 if (!closeLoginDialog)
140 - loginDialog().then()
140 + void loginDialog()
141 }, [loginRequired])
142 return loginRequired ? null : true
143 }
frontend/src/menu.ts
+4 -6
@@ -182,10 +182,8 @@ function LoginButton() {
182
183 export async function deleteFiles(uris: string[]) {
184 const n = uris.length
185 - if (!n) {
186 - alertDialog(t('delete_select', "Select something to delete")).then()
187 - return
188 - }
185 + if (!n)
186 + return void alertDialog(t('delete_select', "Select something to delete"))
187 if (!await confirmDialog(t('delete_confirm', {n}, "Delete {n,plural, one{# item} other{# items}}?")))
188 return false
189 const stop = working()
@@ -198,10 +196,10 @@ export async function deleteFiles(uris: string[]) {
196 const msg = t('delete_completed', {n: n-e}, "Deletion: {n} completed")
197 if (n === 1 && !e)
198 return toast(msg, 'success')
201 - alertDialog(h(Fragment, {},
199 + void alertDialog(h(Fragment, {},
200 msg, e > 0 && t('delete_failed', {n:e}, ", {n} failed"),
201 h('div', { style: { textAlign: 'left', marginTop: '1em', } },
202 ...errors.map(e => h(ErrorMsg, { err: t(err2msg(e.err)) + ': ' + e.uri }))
203 )
206 - )).then()
204 + ))
205 }
\ No newline at end of file
frontend/src/upload.ts
+2 -2
@@ -145,7 +145,7 @@ export function showUpload() {
145 h('button', {
146 className: 'upload-send',
147 onClick() {
148 - enqueue(uploadState.adding).then()
148 + void enqueue(uploadState.adding)
149 clear()
150 }
151 }, t('send_files', { n: adding.length, size }, "Send {n,plural,one{# file} other{# files}}, {size}")),
@@ -270,7 +270,7 @@ subscribe(uploadState, () => {
270 return
271 }
272 if (cur?.entries.length && !uploadState.uploading && !uploadState.paused)
273 - startUpload(cur.entries[0], cur.to).then()
273 + void startUpload(cur.entries[0], cur.to)
274 })
275
276 export async function enqueue(entries: ToUpload[]) {
frontend/src/useFetchList.ts
+1 -1
@@ -90,7 +90,7 @@ export default function useFetchList() {
90 state.stopSearch?.()
91 state.error = xlate(error, HTTP_MESSAGES)
92 if (error === HTTP_UNAUTHORIZED && snap.username)
93 - alertDialog(t('wrong_account', { u: snap.username }, "Account {u} has no access, try another"), 'warning').then()
93 + void alertDialog(t('wrong_account', { u: snap.username }, "Account {u} has no access, try another"), 'warning')
94 state.loginRequired = error === HTTP_UNAUTHORIZED
95 lastReq.current = null
96 continue
mui-grid-form/index.ts
+1 -1
@@ -107,7 +107,7 @@ export function Form<Values extends Dict>({
107 const [phase, setPhase] = useState(Phase.Idle)
108 const submitAfterValidation = useRef(false)
109 const validateUpTo = useRef('')
110 - useEffect(() => void(phaseChange()), [phase]) //eslint-disable-line
110 + useEffect(() => void phaseChange(), [phase]) //eslint-disable-line
111 const keyMet: Dict<number> = {}
112
113 const apis: Dict<FieldApi<unknown>> = {} // consider { [K in keyof Values]?: FieldApi<Values[K]> }
src/acme.ts
+1 -1
@@ -44,7 +44,7 @@ repeat(MINUTE, async stop => {
44 await upnpClient.getGateway() // without this, the next call will break upnp support
45 const res = await upnpClient.getMappings()
46 const leftover = res.find(x => x.description === TEMP_MAP.description) // in case the process is interrupted
47 - if (!leftover) return void(stop()) // we are good
47 + if (!leftover) return void stop() // we are good
48 if (acmeMiddlewareEnabled) return // it doesn't count, as we are in the middle of something. Retry later
49 stop()
50 return upnpClient.removeMapping(TEMP_MAP)
src/api.plugins.ts
+1 -1
@@ -150,7 +150,7 @@ const apis: ApiHandlers = {
150 await stopPlugin(id)
151 await downloadPlugin(found.repo, { branch: online.branch, overwrite: true })
152 if (enabled)
153 - startPlugin(id).then() // don't wait, in case it fails to start
153 + void startPlugin(id) // don't wait, in case it fails to start
154 return {}
155 },
156
src/config.ts
+1 -1
@@ -182,7 +182,7 @@ const saveDebounced = debounceAsync(async () => {
182 await configFile.save(stringify({ ...state, version: VERSION }))
183 .catch(err => console.error('Failed at saving config file, please ensure it is writable.', String(err)))
184 })
185 -export const saveConfigAsap = () => void(saveDebounced())
185 +export const saveConfigAsap = () => void saveDebounced()
186
187 function stringify(obj: any) {
188 return yaml.stringify(obj, { lineWidth:1000 })
src/debounceAsync.ts
+4 -2
@@ -42,8 +42,10 @@ export function debounceAsync<Cancelable extends boolean = false, A extends unkn
42 const waitFor = Math.min(waitingCap, leading ? wait - (now - started) : wait)
43 if (waitFor > 0)
44 await new Promise(resolve => setTimeout(resolve, waitFor))
45 - if (!whoIsWaiting) // canceled
46 - return void(waitingSince = 0) as MaybeR
45 + if (!whoIsWaiting) { // canceled
46 + waitingSince = 0
47 + return undefined as MaybeR
48 + }
49 if (whoIsWaiting !== args) // another fresher call is waiting
50 return latestDebouncer
51 return exec()
src/frontEndApis.ts
+3 -3
@@ -77,7 +77,7 @@ export const frontEndApis: ApiHandlers = {
77 throw new ApiError(HTTP_UNAUTHORIZED)
78 try {
79 await rm(node.source, { recursive: true })
80 - setCommentFor(node.source, '').then()
80 + void setCommentFor(node.source, '')
81 return {}
82 }
83 catch (e: any) {
@@ -104,8 +104,8 @@ export const frontEndApis: ApiHandlers = {
104 await rename(node.source, destSource)
105 getCommentFor(node.source).then(c => {
106 if (!c) return
107 - setCommentFor(node.source!, '').then()
108 - setCommentFor(destSource, c).then()
107 + void setCommentFor(node.source!, '')
108 + void setCommentFor(destSource, c)
109 })
110 }
111 return {}
src/listen.ts
+2 -2
@@ -40,7 +40,7 @@ const commonServerAssign = { headersTimeout: 30_000, timeout: MINUTE } // 'heade
40
41 const considerHttp = debounceAsync(async () => {
42 await waitFor(() => app)
43 - stopServer(httpSrv).then()
43 + void stopServer(httpSrv)
44 httpSrv = Object.assign(http.createServer(commonServerOptions, app.callback()), { name: 'http' }, commonServerAssign)
45 const port = await startServer(httpSrv, { port: portCfg.get(), host: listenInterface.get() })
46 if (!port) return
@@ -81,7 +81,7 @@ export function getCertObject() {
81 }
82
83 const considerHttps = debounceAsync(async () => {
84 - stopServer(httpsSrv).then()
84 + void stopServer(httpsSrv)
85 defaultBaseUrl.proto = 'http'
86 defaultBaseUrl.port = getCurrentPort(httpSrv) ?? 0
87 let port = httpsPortCfg.get()
src/perm.ts
+1 -1
@@ -110,7 +110,7 @@ accountsConfig.sub(obj => {
110 saveAccountsAsap()
111 setHidden(rec, { username: norm })
112 }
113 - updateAccount(rec, {}).then() // work fields
113 + void updateAccount(rec, {}) // work fields
114 })
115 })
116
src/update.ts
+1 -1
@@ -141,7 +141,7 @@ if (argv.updating) { // we were launched with a temporary name, restore original
141 onProcessExit(() =>
142 launch(dest, ['--updated']) ) // launch+sync here would cause old process to stay open, locking ports
143 else
144 - open(dest).then()
144 + void open(dest)
145
146 process.exit()
147 }
src/watchLoad.ts
+2 -2
@@ -29,11 +29,11 @@ export function watchLoad(path:string, parser:(data:any)=>void|Promise<void>, {
29 try {
30 watcher = watch(path, () => {
31 if (!save.isWorking())
32 - debounced().then()
32 + void debounced()
33 })
34 debounced().catch(x=>x)
35 if (immediateFirst)
36 - debounced.flush().then()
36 + void debounced.flush()
37 }
38 catch(e) {
39 retry = setTimeout(install, 3_000) // manual watching until watch is successful