Skip to content

Commit 9611cf6

Browse files
author
hongcai.dhc
committed
feat: support timeout
1 parent c0b87f7 commit 9611cf6

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

index.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
11
'use strict'
22

3-
module.exports = function(emitter, event) {
3+
module.exports = function(emitter, event, timeout) {
44
if (typeof emitter === 'string') {
5+
timeout = event
56
event = emitter
67
emitter = this
78
}
89

910
return new Promise((resolve, reject) => {
1011
const done = event === 'error' ? reject : resolve
12+
if (timeout) {
13+
setTimeout(reject, timeout, new Error('timeout'))
14+
}
1115
emitter.once(event, done)
1216
})
1317
}

test/index.test.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,21 @@ it('await event', () => {
1414
})
1515
})
1616

17+
it('await event with timeout', () => {
18+
return co(function* () {
19+
const e = new EventEmitter()
20+
e.await = awaitEvent
21+
try {
22+
yield e.await('data', 1000)
23+
} catch (e) {
24+
if (e.message === 'timeout') {
25+
return
26+
}
27+
}
28+
throw new Error('boom')
29+
})
30+
})
31+
1732
it('await error', done => {
1833
co(function* () {
1934
const e = new EventEmitter()

0 commit comments

Comments
 (0)