perf: 代码优化 hooks/useFullscreenLoading

This commit is contained in:
pany 2023-05-21 16:02:02 +08:00
parent 17dc453350
commit 2a79acc59a

View File

@ -12,52 +12,24 @@ interface LoadingInstance {
interface UseFullscreenLoading { interface UseFullscreenLoading {
<T extends (...args: any[]) => ReturnType<T>>(fn: T, options?: LoadingOptions): ( <T extends (...args: any[]) => ReturnType<T>>(fn: T, options?: LoadingOptions): (
...args: Parameters<T> ...args: Parameters<T>
) => Promise<ReturnType<T>> | ReturnType<T> ) => Promise<ReturnType<T>>
} }
/** /**
* fnloading * fnloading
* * @param fn
* 1. fn loading
* 2. fn Promiseresolve reject loading
* 3. loading
* @param {*} fn
* @param options LoadingOptions * @param options LoadingOptions
* @returns Function * @returns Promise
*/ */
export const useFullscreenLoading: UseFullscreenLoading = (fn, options = {}) => { export const useFullscreenLoading: UseFullscreenLoading = (fn, options = {}) => {
let loadingInstance: LoadingInstance let loadingInstance: LoadingInstance
const showLoading = (options: LoadingOptions) => { return async (...args) => {
loadingInstance = ElLoading.service(options)
}
const hideLoading = () => {
loadingInstance && loadingInstance.close()
}
const _options = { ...defaultOptions, ...options }
return (...args) => {
try { try {
showLoading(_options) loadingInstance = ElLoading.service({ ...defaultOptions, ...options })
const result = fn(...args) const result = await fn(...args)
const isPromise = result instanceof Promise
// 同步函数
if (!isPromise) {
hideLoading()
return Promise.resolve(result)
}
// Promise
return result return result
.then((res) => { } finally {
return res loadingInstance?.close()
})
.catch((err) => {
throw err
})
.finally(() => {
hideLoading()
})
} catch (err) {
hideLoading()
throw err
} }
} }
} }