node-continuation-local-storage icon indicating copy to clipboard operation
node-continuation-local-storage copied to clipboard

await breaks context

Open mikhailrojo opened this issue 5 years ago • 5 comments

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

mikhailrojo avatar May 20 '20 13:05 mikhailrojo

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.

Qard avatar May 20 '20 19:05 Qard

@mikhailrojo did cls-hooked work for your problem?

karanpvyas avatar Sep 03 '20 12:09 karanpvyas

cls-hooked worked for me.

keshavGaur avatar Apr 02 '21 08:04 keshavGaur

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.

muzammilosman avatar Jan 16 '23 04:01 muzammilosman

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.

Qard avatar Jan 16 '23 07:01 Qard