-
-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy path7-compose-async.js
More file actions
76 lines (62 loc) · 1.71 KB
/
7-compose-async.js
File metadata and controls
76 lines (62 loc) · 1.71 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
'use strict';
const fs = require('node:fs');
const reduceAsync = (items, performer, done, initialValue) => {
const nseted = initialValue === undefined;
let counter = nseted ? 1 : 0;
let previous = nseted ? items[0] : initialValue;
let current = nseted ? items[1] : items[0];
const response = (err, data) => {
if (!err && counter !== items.length - 1) {
counter++;
previous = data;
current = items[counter];
performer(previous, current, response, counter, items);
} else if (done) {
done(err, data);
}
};
performer(previous, current, response, counter, items);
};
const last = (arr) => arr[arr.length - 1];
// funcs - array of parametrs for functions
// args - array of functions
// args[i] - function
// args[-1] - done(err, data)
//
const composeAsync = (funcs, ...args) => (
() => reduceAsync(
args.slice(0, -1),
(params, fn, done) => fn(...[].concat(params).concat(done)),
last(args),
funcs
)
);
// Usage
const randomize = (max) => Math.floor((Math.random() * max));
const wrapAsync = (callback) => setTimeout(callback, randomize(1000));
const read = (file, charset, callback) => {
console.dir({ read: { file, callback } });
fs.readFile(file, charset, callback);
};
const parse = (data, callback) => {
console.dir({ parse: { data, callback } });
wrapAsync(() => {
callback(null, ['Data has been', 'processed!']);
});
};
const preprocess = (data1, data2, callback) => {
console.dir({ preprocess: { data1, data2, callback } });
wrapAsync(() => {
callback(null, data1 + ' ' + data2);
});
};
const cf1 = composeAsync(
['config.txt', 'utf8'],
read,
parse,
preprocess,
(err, data) => {
if (!err) console.log(data);
}
);
cf1();