-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream-flow-async.js
53 lines (46 loc) · 1.21 KB
/
stream-flow-async.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
51
52
53
/**
* This functions
* @param {Readable} stream
* @param {Function} handler - async function meant to process each stream chunk
* @param {Number} flow - amount of concurrent un-resolved async functions
* @return {Promise<unknown>}
*/
const streamFlowAsync = ({
stream,
handler,
flow = 1,
}) => {
const asyncHandlers = [];
const checkIfStreamShouldPause = () => {
if (asyncHandlers.length >= flow && !stream.isPaused()) {
stream.pause();
}
};
const checkIfStreamShouldResume = () => {
if (asyncHandlers.length < flow && stream.isPaused()) {
stream.resume();
}
};
return new Promise((resolve, reject) => {
const handleAsyncHandler = (promise) => {
asyncHandlers.push(promise);
promise
.then(() => {
asyncHandlers.splice(asyncHandlers.indexOf(promise), 1);
checkIfStreamShouldResume();
})
.catch((error) => {
stream.destroy();
reject(error);
});
};
const processData = (chunk) => {
handleAsyncHandler(handler(chunk));
checkIfStreamShouldPause();
};
stream.on('data', processData).on('end', resolve).on('error', reject);
});
};
module.exports = {
streamFlowAsync,
};