Skip to content

Commit

Permalink
feat(asyncLimit): 调整入参
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jun 10, 2023
1 parent cd2cfca commit ef67100
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
6 changes: 3 additions & 3 deletions src/utils/asyncLimit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ describe('asyncLimit', () => {
}
return id
}
const getIdLimit = asyncLimit(getId, 1)
const getIdLimit = asyncLimit(getId)
expect(await getIdLimit(1)).toBe(1)
expect(await getIdLimit(2)).toBe(2)
expect(await Promise.all([getIdLimit(2), getIdLimit(3)])).toEqual([2, 3])
Expand All @@ -27,7 +27,7 @@ describe('asyncLimit', () => {
await wait(500)
return id
}
const getIdLimit = asyncLimit(getId, 1)
const getIdLimit = asyncLimit(getId, { concurrency: 1 })
let id1 = 0
let id2 = 0
let id3 = 0
Expand Down Expand Up @@ -62,7 +62,7 @@ describe('asyncLimit', () => {
await wait(500)
return id
}
const getIdLimit = asyncLimit(getId, 2)
const getIdLimit = asyncLimit(getId, { concurrency: 2 })
let id1 = 0
let id2 = 0
let id3 = 0
Expand Down
14 changes: 12 additions & 2 deletions src/utils/asyncLimit.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
export interface AsyncLimitOptions {
/**
* 并行量。
*
* @default 1
*/
concurrency?: number
}

/**
* 异步函数并行执行限制。
*
* @param asyncFn 异步函数
* @param concurrency 并行量
* @param options 选项
*/
export function asyncLimit<T extends (...args: any[]) => Promise<any>>(
asyncFn: T,
concurrency: number,
options: AsyncLimitOptions = {},
): T {
const { concurrency = 1 } = options
const queue: Array<[args: any[], resolve: (res: any) => any]> = []
let activeCount = 0

Expand Down

0 comments on commit ef67100

Please sign in to comment.