-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel.js
50 lines (45 loc) · 1.06 KB
/
channel.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
48
49
50
"use strict";
const makeChannel = () => {
let handler = void 0;
let isExecuting = false;
const q = [];
const exec = async msg => {
isExecuting = true;
try {
await handler(msg);
} catch (err) {
console.error(err);
}
if (q.length > 0) {
const msgNext = q.shift();
setImmediate(() => exec(msgNext));
} else {
isExecuting = false;
}
};
return {
write: msg => {
if (handler && !isExecuting) {
exec(msg);
} else {
q.push(msg);
}
},
attachHandler: h => {
if (handler) {
throw Error('Handler already attached');
}
if (!h) {
throw Error('Handler cannot be undefined');
}
handler = h;
if (q.length > 0 && !isExecuting) {
const msg = q.shift();
exec(msg);
}
}
};
}
module.exports = {
makeChannel
};