Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. const cls = require('cls-hooked');
  2. const ctx = cls.createNamespace('test-cls-context');
  3.  
  4. // result of this demo: 4 and 13
  5. // despite ctx is "global", every async "context" has it's own strage and values are not mixed between timeouts
  6.  
  7. setTimeout(() => {
  8. ctx.run(() => {
  9. ctx.set('value', 1);
  10. setTimeout(() => {
  11. ctx.set('value', ctx.get('value') + 1);
  12. setTimeout(() => {
  13. ctx.set('value', ctx.get('value') + 2);
  14. process.nextTick(() => {
  15. console.log(ctx.get('value'));
  16. })
  17. })
  18. })
  19. });
  20. });
  21.  
  22. setTimeout(() => {
  23. ctx.run(() => {
  24. ctx.set('value', 10);
  25. setTimeout(() => {
  26. ctx.set('value', ctx.get('value') + 1);
  27. setTimeout(() => {
  28. ctx.set('value', ctx.get('value') + 2);
  29. process.nextTick(() => {
  30. console.log(ctx.get('value'));
  31. })
  32. })
  33. })
  34. });
  35. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement