This repository has been archived by the owner on Sep 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
o.js
96 lines (89 loc) · 2.15 KB
/
o.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
var loopWhile = require('deasync').loopWhile;
function block() {
var done = false;
this.start = function() {
done = false;
};
this.wait = function() {
loopWhile(() => !done);
};
this.done = function() {
done = true;
};
}
var _revoke_all = args => args.map(a => (a && ['object', 'function'].includes(typeof a) && a.__PROXY_TARGET__) || a);
function syncCallback(f) {
var b = new block();
return function(...args) {
if (args.length >= f.length) {
return f(...args);
}
var result;
var error;
args[f.length - 1] = function(err, res) {
b.done();
err ? (error = err) : (result = res);
};
b.start();
f.apply(this, args);
b.wait();
if (error) throw error;
return result;
};
}
function syncPromise(t) {
if (typeof t === 'object' && t != null) {
return new Proxy(t, {
get: function(target, name) {
if (name === '__PROXY_TARGET__') return t;
if ((name !== 'o' && name !== 'oo') || !('then' in target) || name in target) {
return syncPromise(target[name]);
}
var error, result;
var b = new block();
b.start();
target
.then(res => {
result = res;
b.done();
})
.catch(err => {
error = err;
b.done();
});
b.wait();
if (error) {
throw error;
}
return name==='oo'? result : syncPromise(result);
},
});
}
if (typeof t === 'function') {
return new Proxy(
function(...args) {
var _t = (this && this.__PROXY_TARGET__) || this;
var result = t.apply(_t, _revoke_all(args));
return syncPromise(result);
},
{
get: function(_, name) {
if (name === '__PROXY_TARGET__') return t;
if (name === 'call' || name === 'apply') {
return function(...args) {
return syncPromise(t[name](..._revoke_all(args)));
};
}
return syncPromise(t[name]);
},
}
);
}
return t;
}
module.exports = {
syncCallback,
syncPromise,
sp: syncPromise,
sc: syncCallback,
};