-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathe-timeout-callback.js
More file actions
86 lines (77 loc) · 1.98 KB
/
e-timeout-callback.js
File metadata and controls
86 lines (77 loc) · 1.98 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
77
78
79
80
81
82
83
84
85
86
'use strict';
// Wrapper will prevent call after timeout
const timeout = (msec, f) => {
let timer = setTimeout(() => {
if (timer) console.log('Function timedout');
timer = null;
}, msec);
return (...args) => {
if (timer) {
clearTimeout(timer);
timer = null;
return f(...args);
} else {
return [new Error('timeout for callback'), null];
}
};
};
const wrapFunction = f => {
console.log('Wrap function:', f.name);
return (...args) => {
console.log('Called wrapper for:', f.name);
console.dir({ args });
if (args.length > 0) {
const callback = args[args.length - 1];
if (typeof callback === 'function') {
const timeoutCallback = timeout(500, callback);
args[args.length - 1] = (...args) => {
console.log('Callback:', f.name);
const cbRes = timeoutCallback(...args);
console.log('Callback results:', cbRes);
return cbRes;
};
}
}
console.log('Call:', f.name);
console.dir(args);
const result = f(...args);
console.log('Ended wrapper for:', f.name);
console.dir({ result });
return result;
};
};
const cloneInterface = anInterface => {
const clone = {};
const keys = Object.keys(anInterface);
for (const key of keys) {
const fn = anInterface[key];
clone[key] = wrapFunction(fn);
}
return clone;
};
// Usage
const interfaceName = {
methodName(par1, par2, callback) {
console.dir({ par1, par2 });
setTimeout(() => {
callback(null, { field: 'value' });
}, 300);
return par1;
},
methodName2(par1, par2, callback) {
console.dir({ par1, par2 });
setTimeout(() => {
callback(null, { field: 'value2' });
}, 700);
return par1;
},
};
const cloned = cloneInterface(interfaceName);
cloned.methodName('Uno', 'Due', (err, data) => {
console.log({ err, data });
return true;
});
cloned.methodName2('Tre', 'Quattro', (err, data) => {
console.log({ err, data });
return true;
});