-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy path5c-chain.js
63 lines (45 loc) · 1.2 KB
/
5c-chain.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
54
55
56
57
58
59
60
61
62
63
const wrapAsync =
(fn) =>
(...args) =>
setTimeout(() => fn(...args), Math.random() * 1000);
const readConfig = wrapAsync((data, callback) => {
console.log("data - ", data);
console.log("read config");
callback(null, data);
});
const selectFromDb = wrapAsync((query, callback) => {
console.log("query - ", query);
console.log("select from db");
callback(null, { cat: "Evgeniy" });
});
const getHttpPage = wrapAsync((page, callback) => {
console.log("page - ", page);
console.log("Page retrieved");
callback(null, { page: "<html>hello world!</html>" });
});
const chain = () => {
const stack = [];
const executor = () => {
let result = () => null;
const len = stack.length;
for (let i = len - 1; i >= 0; i--) {
const [fn, args] = stack.pop();
const prev = result;
result = (err, data) => {
if (err) return console.error({ err });
fn(...args, prev);
};
}
result();
};
executor.do = (cb, ...args) => {
stack.push([cb, args]);
return executor;
};
return executor;
};
const startChain = chain()
.do(readConfig, "myConfig")
.do(selectFromDb, "select * from cities")
.do(getHttpPage, {});
startChain();