await breaks context
Hi guys
I used your library as a dependency of zipkin package. And I spent 2 days and realized this context doesn't work with await at all
var createNamespace = require('continuation-local-storage').createNamespace;
var session = createNamespace('my session');
const fn = async () => {
console.log('before await => ', session.get('misha')); // before await => yo man
await Promise.resolve(1);
console.log('after await => ', session.get('misha')); // after await => undefined
};
(async () => {
session.run(async() => {
session.set('misha', 'yo man');
fn();
});
})();
So if in my code there are awaits, and in enterprize there are a lot of awaits... then context will be lost just right after await.
v10.16.3 test in
Try cls-hooked, or if you're willing to upgrade your Node.js version, you could give AsyncLocalStorage a try. This module is not really well supported anymore as other modules have filled the gap for more modern versions of Node.js This was mostly targetted at pre-10.x versions of Node.js.
@mikhailrojo did cls-hooked work for your problem?
cls-hooked worked for me.
cls-hooked or AsyncLocalStorage works but it is a wrapper built around async-hooks which is in its experimental state as mentioned here. It is not well recommended for a production ready application.
AsyncLocalStorage has been stable since 16.4.0 and uses a tiny subset of async_hooks which will not change any time soon. Also, the "experimental" status of async_hooks is not a great representation, the "legacy" label is more accurate--it's not likely to change any time soon, but the core team discourages direct use of async_hooks as it exposes internals in ways that could be used unsafely. AsyncLocalStorage does not expose those internals so it's perfectly safe to use and recommended by the core team.