Skip to content

Commit

Permalink
feat(utils): 新增 onceMeanwhile
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jul 15, 2020
1 parent b6d0602 commit bfa244e
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export * from './loadResource'
export * from './md5'
export * from './move'
export * from './omitStrict'
export * from './onceMeanwhile'
export * from './pickStrict'
export * from './placeKitten'
export * from './readFile'
Expand Down
20 changes: 20 additions & 0 deletions src/utils/onceMeanwhile.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { onceMeanwhile } from './onceMeanwhile'
import { wait } from './wait'

describe('onceMeanwhile', () => {
test('表现正常', async () => {
const fn: () => Promise<1> = jest.fn().mockImplementation(async () => {
await wait(50)
return 1
})
const fn$ = onceMeanwhile(fn)

const res = await Promise.all([fn$(), fn$(), fn$(), fn$()])
expect(res).toEqual([1, 1, 1, 1])
expect(fn).toBeCalled().toBeCalledTimes(1)

const r = await fn$()
expect(r).toEqual(1)
expect(fn).toBeCalled().toBeCalledTimes(2)
})
})
29 changes: 29 additions & 0 deletions src/utils/onceMeanwhile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { AnyAsyncFunction } from '../types'
import { isPromiseLike } from './isPromiseLike'

/**
* 同一时间对函数的调用只会触发一次运行。
*
* @param fn 函数
* @returns 返回函数调用结果
*/
export function onceMeanwhile<TFunc extends AnyAsyncFunction>(
fn: TFunc,
): TFunc {
let running = false
let result: Promise<any>
const proxy = (...args: any[]) => {
if (!running) {
running = true
const res = fn(...args)
if (isPromiseLike(res)) {
result = res.then(_ => {
running = false
return _
})
}
}
return result
}
return proxy as any
}

0 comments on commit bfa244e

Please sign in to comment.