Skip to content

Commit

Permalink
fix: internalize utils
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Apr 21, 2021
1 parent 1824223 commit 17d93eb
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
1 change: 0 additions & 1 deletion package.json
Expand Up @@ -47,7 +47,6 @@
"devDependencies": {
"@antfu/eslint-config": "^0.6.2",
"@antfu/ni": "^0.5.7",
"@antfu/utils": "^0.1.0",
"@iconify/json": "^1.1.330",
"@rollup/plugin-replace": "^2.4.2",
"@rollup/plugin-typescript": "^8.2.1",
Expand Down
2 changes: 1 addition & 1 deletion packages/core/usePermission/index.ts
@@ -1,5 +1,5 @@
import { Ref, ref } from 'vue-demi'
import { createSingletonPromise } from '@antfu/utils'
import { createSingletonPromise } from '@vueuse/shared'
import { useEventListener } from '../useEventListener'
import { ConfigurableNavigator, defaultNavigator } from '../_configurable'

Expand Down
39 changes: 39 additions & 0 deletions packages/shared/utils/index.ts
Expand Up @@ -15,6 +15,45 @@ export function promiseTimeout(
})
}

export interface SingletonPromiseReturn<T> {
(): Promise<T>
/**
* Reset current staled promise.
* await it to have proper shutdown.
*/
reset: () => Promise<void>
}

/**
* Create singleton promise function
*
* @example
* ```
* const promise = createSingletonPromise(async () => { ... })
*
* await promise()
* await promise() // all of them will be bind to a single promise instance
* await promise() // and be resolved together
* ```
*/
export function createSingletonPromise<T>(fn: () => Promise<T>): SingletonPromiseReturn<T> {
let _promise: Promise<T> | undefined

function wrapper() {
if (!_promise)
_promise = fn()
return _promise
}
wrapper.reset = async() => {
const _prev = _promise
_promise = undefined
if (_prev)
await _prev
}

return wrapper
}

export function invoke<T>(fn: () => T): T {
return fn()
}
Expand Down

0 comments on commit 17d93eb

Please sign in to comment.