-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
83 lines (72 loc) · 2.4 KB
/
index.js
File metadata and controls
83 lines (72 loc) · 2.4 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
'use strict';
const Promise = require('bluebird');
const EventEmitter = require('events').EventEmitter;
module.exports = class ExtraEmitter extends EventEmitter {
/**
* @static
* @param {EventEmitter} from
* @param {EventEmitter} to
* @param {String|String[]} event or array of events to passthrough
*/
static passthroughEvent(...args) {
return mkPassthroughFn('emit')(...args);
}
/**
* @static
* @param {EventEmitter} from
* @param {EventEmitter} to
* @param {String|String[]} event or array of events to passthrough
*/
static passthroughEventAsync(...args) {
return mkPassthroughFn('emitAndWait')(...args);
}
/**
* Emit event and wait for all async handler execution results
* @param {String} event
* @param {any} args
* @returns {Promise}
*/
emitAndWait(event, ...args) {
const asyncHandlers = this.listeners(event)
.map((listener) => Promise.method(listener).apply(this, markAsAsync(args)));
return waitForResults(asyncHandlers);
}
/**
* Subscribe on event(s) from given emitter and trigger the same event(s) from itself
* @param {EventEmitter} emitter
* @param {String|String[]} event or array of events to passthrough
*/
passthroughEvent(emitter, event) {
if (Array.isArray(event)) {
event.forEach(this.passthroughEvent.bind(this, emitter));
return;
}
emitter.on(event, (...args) => {
if (args.includes('async')) {
return this.emitAndWait(event, ...args);
} else {
this.emit(event, ...args);
}
});
}
};
function markAsAsync(args) {
return args.includes['async'] ? args : args.concat('async');
}
function waitForResults(promises) {
return Promise.all(promises.map((p) => p.reflect()))
.then((res) => {
const firstRejection = res.find((v) => v.isRejected());
return firstRejection ? Promise.reject(firstRejection.reason()) : res.map((r) => r.value());
});
}
function mkPassthroughFn(methodName) {
const passEvents = (from, to, event) => {
if (typeof event === 'string') {
from.on(event, (...args) => to[methodName](event, ...args));
return;
}
event.forEach((event) => passEvents(from, to, event));
};
return passEvents;
}