UNPKG

@newdash/newdash

Version:

javascript/typescript utility library

50 lines (49 loc) 1.26 kB
/** * @private * @internal * @ignore */ type ReleaseFunction = () => void; export declare class Semaphore { private tasks; private count; private defaultAcquireTimeout; /** * Semaphore implementation for async js operations, used for resource limit or pool implementation * * @since 5.15.0 * @category Functional * * @example * * ```ts * const sem = new Semaphore(10) * * async call_api(payload: any) { * const release = await sem.acquire() * // ... * // this block, will be execute with 10 concurrency limit * release() * } * * ``` */ constructor(count: number, defaultAcquireTimeout?: number); private _schedule; /** * acquire a permit from sem * * @param timeout wait before timeout, if not set, will wait forever * @returns release function, which used for release a permit to sem */ acquire(timeout?: number): Promise<ReleaseFunction>; /** * run an async function with sem limit * * @param f async runner function * @param timeout wait timeout before wait * @returns */ use<T>(f: () => Promise<T>, timeout?: number): Promise<T>; } export default Semaphore;