Skip to content

Commit

Permalink
utils: Add timeout for waitForEvent method
Browse files Browse the repository at this point in the history
  • Loading branch information
atinux committed Oct 18, 2017
1 parent b1dce49 commit 12944a6
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ Methods:
- `ok(promise: Object): Promise`
- `cb(fn: Function, ...args: any[]): Promise`
- `waitFor(ms: number): Promise`
- `waitForEvent(emitter: EventEmitter, eventName: string): Promise<Array>`
- `waitForEvent(emitter: EventEmitter, eventName: string, timeout: number = -1): Promise<Array>`
- `asyncObject(obj: Object): Promise<Object>`

## Credits
Expand Down
13 changes: 10 additions & 3 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,16 @@ exports.waitFor = function (ms) {
/*
** waitForEvent(emmiter, eventName)
*/
exports.waitForEvent = function (emmiter, eventName) {
return new Promise((resolve) => {
emmiter.once(eventName, (...args) => resolve([...args]))
exports.waitForEvent = function (emmiter, eventName, timeout = -1) {
return new Promise((resolve, reject) => {
let resolveCalled = false
const r = (...args) => {
if (resolveCalled) return
resolve(...args)
resolveCalled = true
}
emmiter.once(eventName, (...args) => r([...args]))
if (timeout >= 0) setTimeout(() => reject('Timeout'), timeout)
})
}

Expand Down

0 comments on commit 12944a6

Please sign in to comment.