mirror of
https://github.com/woodchen-ink/clash-and-dashboard.git
synced 2025-07-18 14:01:56 +08:00
Chore: improve createAsyncSingleton
This commit is contained in:
parent
da255fa38c
commit
1686f50b37
@ -1,29 +1,15 @@
|
||||
export function createAsyncSingleton<T> (fn: () => Promise<T>): () => Promise<T> {
|
||||
let promise: Promise<T> | null = null
|
||||
let instance: T | null = null
|
||||
|
||||
async function fetch () {
|
||||
return async function () {
|
||||
if (promise) {
|
||||
return promise
|
||||
}
|
||||
|
||||
promise = fn()
|
||||
return promise
|
||||
.then(r => {
|
||||
promise = null
|
||||
return r
|
||||
})
|
||||
.catch(e => {
|
||||
promise = null
|
||||
return e
|
||||
throw e
|
||||
})
|
||||
}
|
||||
|
||||
return async function () {
|
||||
if (instance) {
|
||||
return instance
|
||||
}
|
||||
|
||||
return fetch()
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user