Chore: improve createAsyncSingleton

This commit is contained in:
Dreamacro 2019-09-30 16:51:49 +08:00
parent da255fa38c
commit 1686f50b37

View File

@ -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()
}
}