othiym23 / node-continuation-local-storage

implementation of https://github.com/joyent/node/issues/5243
BSD 2-Clause "Simplified" License
1.13k stars 207 forks source link

await breaks context #143

Open mikhailrojo opened 4 years ago

mikhailrojo commented 4 years ago

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

Qard commented 4 years ago

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.

karanpvyas commented 4 years ago

@mikhailrojo did cls-hooked work for your problem?

keshavGaur commented 3 years ago

cls-hooked worked for me.

muzammilosman commented 1 year ago

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.

Qard commented 1 year ago

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.