Skip to content

Commit

Permalink
feat(wait): 支持取消等待
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jul 9, 2019
1 parent 89087af commit 0cb4ec0
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
10 changes: 10 additions & 0 deletions src/wait.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,13 @@ test('表现正常', async () => {
true,
)
})

test('可取消等待', async () => {
const cb = jest.fn()
const w = wait(500)
w.then(cb)
w.cancel()
await wait(600)

expect(cb).toBeCalledTimes(0)
})
18 changes: 15 additions & 3 deletions src/wait.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
export interface WaitReturn extends Promise<void> {
/**
* 取消等待,不执行后续逻辑。
*/
cancel: () => void,
}

/**
* 等待一段时间。
*
Expand All @@ -9,8 +16,13 @@
* })
* ```
*/
export function wait(milliseconds: number): Promise<void> {
return new Promise(
resolve => setTimeout(resolve, milliseconds),
export function wait(milliseconds: number): WaitReturn {
let timer!: number
const p = new Promise(
resolve => {
timer = setTimeout(resolve, milliseconds) as any
},
)
;(p as any).cancel = () => clearTimeout(timer)
return p as any
}

0 comments on commit 0cb4ec0

Please sign in to comment.