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> { export function createAsyncSingleton<T> (fn: () => Promise<T>): () => Promise<T> {
let promise: Promise<T> | null = null let promise: Promise<T> | null = null
let instance: T | null = null
async function fetch () { return async function () {
if (promise) { if (promise) {
return promise return promise
} }
promise = fn() promise = fn()
return promise return promise
.then(r => {
promise = null
return r
})
.catch(e => { .catch(e => {
promise = null promise = null
return e throw e
}) })
} }
return async function () {
if (instance) {
return instance
}
return fetch()
}
} }