Skip to content

Commit

Permalink
feat: createPromiseLock
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Aug 25, 2021
1 parent 56ddddd commit cbbf7b8
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/promise.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { remove } from './array'
import { Fn } from './types'

export interface SingletonPromiseReturn<T> {
Expand Down Expand Up @@ -50,3 +51,44 @@ export function sleep(ms: number, callback?: Fn<any>) {
}, ms),
)
}

/**
* Create a promise lock
*
* @example
* ```
* const lock = createPromiseLock()
*
* lock.run(async () => {
* await doSomething()
* })
*
* // in anther context:
* await lock.wait() // it will wait all tasking finished
* ```
*/
export function createPromiseLock() {
const locks: Promise<any>[] = []

return {
async run<T = void>(fn: () => Promise<T>): Promise<T> {
const p = fn()
locks.push(p)
try {
return await p
}
finally {
remove(locks, p)
}
},
async wait(): Promise<void> {
await Promise.allSettled(locks)
},
isWaiting() {
return Boolean(locks.length)
},
clear() {
locks.length = 0
},
}
}

0 comments on commit cbbf7b8

Please sign in to comment.