Skip to content

Commit

Permalink
feat(wait): 新增 wait.reject
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Dec 4, 2020
1 parent 8e99c2f commit e9314c8
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
22 changes: 21 additions & 1 deletion src/utils/wait.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { run } from './run'
import { wait } from './wait'

describe(wait.name, () => {
describe('wait', () => {
test('表现正常', async () => {
const start = Date.now()
await wait(110)
Expand All @@ -17,3 +18,22 @@ describe(wait.name, () => {
expect(cb).not.toBeCalled()
})
})

describe('wait.reject', () => {
test('表现正常', async () => {
const start = Date.now()
const [err] = await run(() => wait.reject(110))
expect(err).not.toBeNull()
const end = Date.now()
expect(end - start >= 100).toBeTrue()
})

test('可取消等待', async () => {
const cb = jest.fn()
const w = wait.reject(100)
w.catch(cb)
w.cancel()
await wait(100)
expect(cb).not.toBeCalled()
})
})
19 changes: 19 additions & 0 deletions src/utils/wait.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,22 @@ export function wait(milliseconds: number): WaitResult {
result.cancel = () => clearTimeout(timer)
return result
}

/**
* 等待一段时间后 reject。
*
* @public
* @param milliseconds 等待时间(毫秒)
* @example
* ```typescript
* wait.reject(1000).catch(() => {
* console.log('ok')
* }) // => 1秒后在控制台打印字符串: ok
* ```
*/
wait.reject = function reject(milliseconds: number): WaitResult {
const waitRes = wait(milliseconds)
const res: WaitResult = waitRes.then(() => Promise.reject()) as any
res.cancel = waitRes.cancel
return res
}

0 comments on commit e9314c8

Please sign in to comment.