-
Notifications
You must be signed in to change notification settings - Fork 0
/
continuation-local-variable.js
51 lines (38 loc) · 1.05 KB
/
continuation-local-variable.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
'use strict';
const async_hooks = require('async_hooks');
const fs = require('fs');
const util = require('util');
function debug(...args) {
fs.writeSync(1, `${util.format(...args)}\n`);
}
class Variable {
constructor(name) {
var self = this;
self.name = name;
self.memo = {};
self.value = undefined;
self.hook = async_hooks.createHook({
init(asyncId, type, triggerAsyncId, resource) { self.save(asyncId); },
before(asyncId) { self.restore(asyncId); },
after(asyncId) { },
destroy(asyncId) { self.destroy(asyncId); }
});
self.hook.enable();
}
set(value) { this.value = value; }
get(value) { return this.value; }
save(asyncId) { this.memo[asyncId] = this.value; }
restore(asyncId) { this.value = this.memo[asyncId]; }
destroy(asyncId) { delete this.memo[asyncId]; }
}
const VARIABLES = {};
module.exports = {
create: function (name) {
const variable = new Variable(name);
VARIABLES[name] = variable;
return variable;
},
find: function (name) {
return VARIABLES[name];
}
}