Skip to content

Instantly share code, notes, and snippets.

@xingoxu
Created June 27, 2020 10:38
Show Gist options
  • Select an option

  • Save xingoxu/590e7f99658ea160b1f77cdb4e956637 to your computer and use it in GitHub Desktop.

Select an option

Save xingoxu/590e7f99658ea160b1f77cdb4e956637 to your computer and use it in GitHub Desktop.
A simple implementation of CLS under Node.js
const {
executionAsyncId,
createHook,
} = require("async_hooks");
const { writeSync: fsWrite } = require("fs");
const log = (...args) => fsWrite(1, `${args.join(" ")}\n`);
const Storage = {};
Storage[executionAsyncId()] = {};
createHook({
init(asyncId, _type, triggerId, _resource) {
// log(asyncId, Storage[asyncId]);
Storage[asyncId] = {};
if (Storage[triggerId]) {
Storage[asyncId] = { ...Storage[triggerId] };
}
},
after(asyncId) {
delete Storage[asyncId];
},
destroy(asyncId) {
delete Storage[asyncId];
},
}).enable();
class CLS {
static get(key) {
return Storage[executionAsyncId()][key];
}
static set(key, value) {
Storage[executionAsyncId()][key] = value;
}
}
// --- seperate line ---
function timeout(id) {
CLS.set('a', id)
setTimeout(() => {
const a = CLS.get('a')
console.log(a)
}, Math.random() * 1000);
}
timeout(1)
timeout(2)
timeout(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment