Template
1
0
mirror of https://github.com/un-pany/v3-admin-vite.git synced 2025-04-20 19:09:21 +08:00

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