Skip to content

Instantly share code, notes, and snippets.

@Olegas
Created June 4, 2019 22:18
Show Gist options
  • Save Olegas/23a6fcff0e726490d97907cd4f0ad08f to your computer and use it in GitHub Desktop.
Save Olegas/23a6fcff0e726490d97907cd4f0ad08f to your computer and use it in GitHub Desktop.
const cls = require('cls-hooked');
const ctx = cls.createNamespace('test-cls-context');
// result of this demo: 4 and 13
// despite ctx is "global", every async "context" has it's own strage and values are not mixed between timeouts
setTimeout(() => {
ctx.run(() => {
ctx.set('value', 1);
setTimeout(() => {
ctx.set('value', ctx.get('value') + 1);
setTimeout(() => {
ctx.set('value', ctx.get('value') + 2);
process.nextTick(() => {
console.log(ctx.get('value'));
})
})
})
});
});
setTimeout(() => {
ctx.run(() => {
ctx.set('value', 10);
setTimeout(() => {
ctx.set('value', ctx.get('value') + 1);
setTimeout(() => {
ctx.set('value', ctx.get('value') + 2);
process.nextTick(() => {
console.log(ctx.get('value'));
})
})
})
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment