1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | const nowAndTimers = require('./now-and-timers');
|
11 |
|
12 | function controlFlow(channel) {
|
13 | let sending = false;
|
14 |
|
15 | const buffer = [];
|
16 | const deliverNext = () => {
|
17 | if (!channel.connected) {
|
18 | buffer.length = 0;
|
19 | }
|
20 |
|
21 | if (buffer.length === 0) {
|
22 | sending = false;
|
23 | return;
|
24 | }
|
25 |
|
26 | channel.send(buffer.shift(), deliverNext);
|
27 | };
|
28 |
|
29 | return message => {
|
30 | if (!channel.connected) {
|
31 | return;
|
32 | }
|
33 |
|
34 | buffer.push(message);
|
35 | if (!sending) {
|
36 | sending = true;
|
37 | nowAndTimers.setImmediate(deliverNext);
|
38 | }
|
39 | };
|
40 | }
|
41 |
|
42 | exports.controlFlow = controlFlow;
|