forked from justadudewhohacks/opencv4nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
promisify.js
37 lines (30 loc) · 1.03 KB
/
promisify.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
const isFn = obj => typeof obj === 'function';
const isAsyncFn = fn => fn.prototype.constructor.name.endsWith('Async');
const promisify = (fn) => function () {
if (isFn(arguments[arguments.length - 1])) {
return fn.apply(this, arguments);
}
return new Promise((resolve, reject) => {
const args = Array.prototype.slice.call(arguments);
args.push(function(err, res) {
if (err) {
return reject(err);
}
return resolve(res);
});
fn.apply(this, args);
});
};
module.exports = (cv) => {
const fns = Object.keys(cv).filter(k => isFn(cv[k])).map(k => cv[k]);
const asyncFuncs = fns.filter(isAsyncFn);
const clazzes = fns.filter(fn => !!Object.keys(fn.prototype).length);
clazzes.forEach((clazz) => {
const protoFnKeys = Object.keys(clazz.prototype).filter(k => isAsyncFn(clazz.prototype[k]));
protoFnKeys.forEach(k => clazz.prototype[k] = promisify(clazz.prototype[k]));
});
asyncFuncs.forEach((fn) => {
cv[fn.prototype.constructor.name] = promisify(fn);
});
return cv;
};