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

Is there a safe & fast way to check if I'm in a context right now? #93

Closed osher closed 7 years ago

osher commented 7 years ago

My task now is to glue few legacy codes that use some singleton that was replaced in modern codes with a contextified instance.

I need to use the contextified instance whenever it's available, and fallback to the infamous singleton whenver it's not found.

I did notice that when I try to get or set a value when I'm not in a context of an async handler an exception is thrown.

The access to this model is very common. I cannot afford to try { return ns.get(name) } catch(e) { return fallbackToSingleton }.

Is there a way I can check if I'm in a context or not?

osher commented 7 years ago

aha. I take it back. the throw is only for .set

so the right way is probably return ns.get(name) || fallbackToSingleton

If I'm mistaking - let me know

Qard commented 7 years ago

That's an appropriate way to handle it. 👍