Created
June 27, 2020 10:38
-
-
Save xingoxu/590e7f99658ea160b1f77cdb4e956637 to your computer and use it in GitHub Desktop.
A simple implementation of CLS under Node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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