-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
47 lines (39 loc) · 1.49 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Events with await method
**/
'use strict';
const assert = require('assert');
const debug = require('debug')('await-events');
const EventEmitter = require('events');
class AwaitEvent extends EventEmitter {
async await(...args) {
return await AwaitEvent.await(this, ...args);
}
static async await(...args) {
if ('string' === typeof args[0]) {
args.unshift(this);
}
let [emitter, eventName, errorEventName] = args;
debug(`await ${eventName}`);
assert(emitter instanceof Object && emitter.once instanceof Function
&& emitter.removeListener instanceof Function, 'emitter should be an EventEmitter or something like');
assert('string' === typeof eventName, 'event name should be a string');
errorEventName = errorEventName || 'error';
assert('string' === typeof errorEventName, 'error event name should be a string');
return new Promise((resolve, reject) => {
const res = (...args) => {
debug(`await ${eventName} OK`);
emitter.removeListener(errorEventName, rej);
resolve(...args);
};
const rej = (...args) => {
debug(`await ${eventName} ERROR`);
emitter.removeListener(eventName, res);
reject(...args);
};
emitter.once(eventName, res);
emitter.once(errorEventName, rej);
});
}
}
module.exports = AwaitEvent;