move callback function outside try catch block, refactor logic

pull/3385/head
Yuxuan Zhang 2 years ago
parent 8849d85523
commit 9281648b3e
No known key found for this signature in database
GPG Key ID: 6910B04F3351EF7D

@ -4,7 +4,7 @@ import humanizeDuration from 'humanize-duration'
export const okMark = '\x1b[32m✓\x1b[0m'
export const failMark = '\x1b[31m✖\x1b[0m'
type UpdateHandle = (done: number, total?: number) => any
export type UpdateHandle = (done: number, total?: number) => any
export async function task<T>(
taskName: string,
@ -13,23 +13,24 @@ export async function task<T>(
const spinner = ora({ discardStdin: false })
spinner.start(taskName + '...')
let symbol = okMark
const updateHandle: UpdateHandle = (done, total) => {
if (total === undefined) {
spinner.text = `${taskName} [ ${done} ]`
} else {
// match length to display them in same width
const _total = `${total}`
const _done = `${done}`.padStart(_total.length, ' ')
spinner.text = `${taskName} [ ${_done} / ${_total} ]`
}
}
const timeStart = performance.now()
let success = true
try {
const updateHandle: UpdateHandle = (done, total) => {
if (total === undefined) {
spinner.text = `${taskName} [ ${done} ]`
} else {
// match length to display them in same width
const _total = `${total}`
const _done = `${done}`.padStart(_total.length, ' ')
spinner.text = `${taskName} [ ${_done} / ${_total} ]`
}
}
return await task(updateHandle)
} catch (e) {
symbol = failMark
success = false
throw e
} finally {
const timeEnd = performance.now()
@ -37,6 +38,7 @@ export async function task<T>(
maxDecimalPoints: 2
})
const text = `${taskName} - ${duration}`
const symbol = success ? okMark : failMark
spinner.stopAndPersist({ symbol, text })
}
}

Loading…
Cancel
Save