import { remove } from './array' ; import type { Fn } from './types' ; export interface SingletonPromiseReturn < T > { ( ) : Promise < T > ; /**
     * Reset current staled promise.
     * Await it to have proper shutdown.
     */ reset : ( ) => Promise < void > ; } example export function createSingletonPromise < T > ( fn ) { let _promise ; function wrapper ( ) { if ( ! _promise ) _promise = fn ( ) ; return _promise ; } wrapper . reset = async ( ) => { const _prev = _promise ; _promise = undefined ; if ( _prev ) await _prev ; } ; return wrapper ; } /**
 * Promised `setTimeout`
 */ export function sleep ( ms , callback ? ) { return new Promise < void > ( resolve => setTimeout ( async ( ) => { await callback ?. ( ) ; resolve ( ) ; } , ms ) ) ; } example export function createPromiseLock ( ) { const locks = [ ] ; return { async run < T = void > ( fn ) { const p = fn ( ) ; locks . push ( p ) ; try { return await p ; } finally { remove ( locks , p ) ; } } , async wait ( ) { await Promise . allSettled ( locks ) ; } , isWaiting ( ) { return Boolean ( locks . length ) ; } , clear ( ) { locks . length = 0 ; } , } ; }