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:
parent
17dc453350
commit
2a79acc59a
@ -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>>
|
||||
}
|
||||
|
||||
/**
|
||||
* 传入一个函数 fn,在它执行周期内,加上「全屏」loading,
|
||||
* 如果:
|
||||
* 1. fn 如果是同步函数,执行结束后隐藏 loading
|
||||
* 2. fn 如果是 Promise,resolve 或 reject 后隐藏 loading
|
||||
* 3. 报错后隐藏 loading 并抛出错误
|
||||
* @param {*} fn 要执行的函数
|
||||
* 传入一个函数 fn,在它执行周期内,加上「全屏」loading
|
||||
* @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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user