forked from blikblum/nextbone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
class-utils.js
43 lines (36 loc) · 1.26 KB
/
class-utils.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
const resolved = Promise.resolve();
const startPromiseMap = new WeakMap();
const getStartPromise = (instance, startMethod) => {
let result = typeof startMethod === 'function' ? startPromiseMap.get(instance) : resolved;
if (!result) {
result = resolved.then(() => startMethod.call(instance));
startPromiseMap.set(instance, result);
}
return result;
};
const createAsyncMethod = descriptor => {
const method = descriptor.value;
descriptor.value = function(...args) {
const promise = getStartPromise(this, this.start).then(() => method.apply(this, args));
promise.catch(err => {
typeof this.onError === 'function' && this.onError(err);
});
return promise;
};
};
export const asyncMethod = (protoOrDescriptor, methodName, propertyDescriptor) => {
if (typeof methodName !== 'string') {
// spec decorator
createAsyncMethod(protoOrDescriptor.descriptor);
return protoOrDescriptor;
}
createAsyncMethod(propertyDescriptor);
};
export const defineAsyncMethods = (klass, methodNames) => {
const proto = klass.prototype;
methodNames.forEach(methodName => {
const desc = Object.getOwnPropertyDescriptor(proto, methodName);
asyncMethod(proto, methodName, desc);
Object.defineProperty(proto, methodName, desc);
});
};