-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
39 lines (32 loc) · 927 Bytes
/
index.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
'use strict';
const { promisify } = require('util');
const proxyMap = new WeakMap();
const asyncMap = new WeakMap();
const proxyHandler = {
get (target, prop) {
if (isFunction(target[prop])) {
const fn = target[prop];
return from(asyncMap, fn,
fn.length
? (...args) => promisify(fn).apply(target, args)
: () => Promise.resolve(fn.call(target))
);
}
return target[prop];
},
apply (fn, thisValue, args) {
return fn.length
? from(asyncMap, fn, promisify(fn).apply(thisValue, args))
: Promise.resolve(fn.call(thisValue));
}
};
function doAsync (object) {
return from(proxyMap, object, new Proxy(object, proxyHandler));
}
function from (map, key, value) {
return map.get(key) || map.set(key, value).get(key);
}
function isFunction (fn) {
return !!(Object.prototype.toString.call(fn) === '[object Function]');
}
module.exports = doAsync;