Skip to content

Commit

Permalink
feat(wait): 支持返回值
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Dec 4, 2020
1 parent e9314c8 commit 2d1b63e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
8 changes: 8 additions & 0 deletions src/utils/wait.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ describe('wait', () => {
await wait(100)
expect(cb).not.toBeCalled()
})

test('返回值正常', async () => {
expect(await wait(10, '120')).toBe('120')
})
})

describe('wait.reject', () => {
Expand All @@ -36,4 +40,8 @@ describe('wait.reject', () => {
await wait(100)
expect(cb).not.toBeCalled()
})

test('返回值正常', async () => {
expect(await wait.reject(10, '120').catch(res => res)).toBe('120')
})
})
21 changes: 13 additions & 8 deletions src/utils/wait.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,31 @@
/**
* @public
*/
export interface WaitResult extends Promise<void> {
export interface WaitResult<T> extends Promise<T> {
/**
* 取消等待,不执行后续逻辑。
*/
cancel: () => void
}

/**
* 等待一段时间。
* 等待一段时间 resolve
*
* @public
* @param milliseconds 等待时间(毫秒)
* @param value resolve 值
* @example
* ```typescript
* wait(1000).then(() => {
* console.log('ok')
* }) // => 1秒后在控制台打印字符串: ok
* ```
*/
export function wait(milliseconds: number): WaitResult {
export function wait<T>(milliseconds: number, value?: T): WaitResult<T> {
let timer: any
const result = new Promise(resolve => {
timer = setTimeout(resolve, milliseconds)
}) as WaitResult
const result = new Promise<T | undefined>(resolve => {
timer = setTimeout(() => resolve(value), milliseconds)
}) as WaitResult<T>
result.cancel = () => clearTimeout(timer)
return result
}
Expand All @@ -34,16 +35,20 @@ export function wait(milliseconds: number): WaitResult {
*
* @public
* @param milliseconds 等待时间(毫秒)
* @param value reject 值
* @example
* ```typescript
* wait.reject(1000).catch(() => {
* console.log('ok')
* }) // => 1秒后在控制台打印字符串: ok
* ```
*/
wait.reject = function reject(milliseconds: number): WaitResult {
wait.reject = function reject(
milliseconds: number,
value?: any,
): WaitResult<void> {
const waitRes = wait(milliseconds)
const res: WaitResult = waitRes.then(() => Promise.reject()) as any
const res: WaitResult<void> = waitRes.then(() => Promise.reject(value)) as any
res.cancel = waitRes.cancel
return res
}

0 comments on commit 2d1b63e

Please sign in to comment.