Skip to content

Commit

Permalink
feat(loopUntil): 可不传 fn
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jul 13, 2022
1 parent 859b8b4 commit f8fc3b2
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
16 changes: 16 additions & 0 deletions src/utils/loopUntil.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,20 @@ describe('loopUntil', () => {
).rejects.toBeInstanceOf(LoopUntilRetryLimitExceededError)
expect(i).toBe(6)
})

test('异步正常2', async () => {
const i = 0
const fn = jest.fn().mockImplementation(
() =>
// @ts-ignore
i === 0,
)
expect(
await loopUntil(fn, {
retryDelay: 0,
retryLimit: 1,
}),
).toBe(undefined)
expect(fn).toBeCalled()
})
})
25 changes: 21 additions & 4 deletions src/utils/loopUntil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,17 @@ export interface LoopUntilOptions {

export class LoopUntilRetryLimitExceededError extends Error {}

export async function loopUntil<T>(
fn: () => AsyncOrSync<T>,
condition: (res: T) => AsyncOrSync<boolean>,
options: LoopUntilOptions,
): Promise<T>

export async function loopUntil(
condition: () => AsyncOrSync<boolean>,
options: LoopUntilOptions,
): Promise<void>

/**
* 循环调用某个函数直至达到某个条件后返回调用结果。
*
Expand All @@ -24,14 +35,20 @@ export class LoopUntilRetryLimitExceededError extends Error {}
* @param options 选项
*/
export async function loopUntil<T>(
fn: () => AsyncOrSync<T>,
condition: (res: T) => AsyncOrSync<boolean>,
options: LoopUntilOptions,
fn: any,
condition: any,
options?: any,
): Promise<T> {
if (options == null) {
options = condition
condition = fn
fn = undefined
}

let retryCount = 0
// eslint-disable-next-line no-constant-condition
while (true) {
const res = await fn()
const res = fn ? await fn() : undefined
if (await condition(res)) {
return res
}
Expand Down

0 comments on commit f8fc3b2

Please sign in to comment.