1

In node how to declare global variable only available for current execution context, not needed in asynchronous callback?

var obj = 'something'

setTimeout( function(){
// callback context
// i want to get null or undefined value for obj
console.log(obj) 
}, 500);
  • Can you show a real world case of what you're trying to accomplish. I do not understand the question or what you are trying to do. There literally are no such things as `global` variables only available to the current execution scope. By definition a `global` variable is available to all scopes. You can declare a variable in your own scope that is only available within that scope (but that's not a global). So, global scope or only private scope? Pick one, not both. – jfriend00 Dec 07 '17 at 07:47
  • developing montoring solution for nodejs web application. whenever new request comes I am setting current request in global object, any asynchronous mysql query is invoked at that another request is start processing that overrides current request in global object so that when mysql call completes that mysql query is associated with wrong transaction. atleast if current transaction shows null in mysql call back that query will not be associated with wrong request. – stupidloser Dec 07 '17 at 07:57
  • You can't do that in Javascript. There is no such thing as global state that attaches itself only to the current request handlers. Something similar was asked for here [How to include session ID for request in every log statement](https://stackoverflow.com/questions/47584374/expressjs-include-session-id-in-every-log-statement/47584613#47584613). You can't do it that way. – jfriend00 Dec 07 '17 at 08:09
  • Instead, you must learn how to write proper asynchronous code in Javascript where you pass state down to places that need it and you communicate back asynchronous results with either callbacks or by returning promises. You don't create request-specific global state and try to use that. Javascript does not work that way. The only way to do that would be to fire up a new node.js process for every request and let the state be global in each new process that is only serving one request. That would ruin node.js scalability, dumbing it down to something worse than PHP. – jfriend00 Dec 07 '17 at 08:11
  • If you showed enough of the actual code for the actual problem you are trying to solve, we could likely advise on a supported way to solve your problem. – jfriend00 Dec 07 '17 at 08:12

0 Answers0