0

Is it possible to define a global variable in a node.js function?

I want use the ko variable (declared in the getNumbers function) in other functions

function getNumbers(callback) {
    result = cio.query("SELECT numbers FROM rooms WHERE durum='1'", function (err, result) {
        if (err) throw err;
        callback((result.length > 0) ? result[0].numbers : "");
    });
}

var ko = getNumbers(function (result) {

console.log(result)
});


 var zo = ko;

"undefined"

46,16,55,12,74,48,77,42,4,29,14,81,13,35,39,85,7,54,27,66,41,9,17,82,31,21,57,79,62,56,11,49,3,33,64,8,83,88,61,18,58,63,51,90,22,71,67,69,75,6,2,34,30,25,38,28,68,5,50,15,87,19,65,36,45,24
C:\wamp64\www\node\st\rooms.js:497
        var datadad = zo[Math.floor(Math.random()*zo.length)];
                                                     ^

TypeError: Cannot read property 'length' of undefined
    at sayiver (C:\wamp64\www\node\st\rooms.js:497:54)
    at Timeout._onTimeout (C:\wamp64\www\node\st\rooms.js:513:5)
    at ontimeout (timers.js:436:11)
    at tryOnTimeout (timers.js:300:5)
    at listOnTimeout (timers.js:263:5)
    at Timer.processTimers (timers.js:223:10)
7
  • define "ko" on the top Commented Jan 2, 2019 at 7:24
  • "in other functions" - where do you mean to define those functions? If they are part of the same module (basically, "file") as the getNumbers function, this will work. If you want to use the resulting value 'ko' outside of this module, you will need to export it. Commented Jan 2, 2019 at 7:26
  • @priyanshisrivastava Defining "ko" at topdoesn't matter, It is gonna hoist at the top anyways. You have to return value of result inside getNumbers functions in order to receie values. var ko = getNumbers(function (result) {return result}); Commented Jan 2, 2019 at 7:31
  • Returning a value like that wouldn't work since it's asynchronous operation. Your return clause value is inside the callback, not getNumbers. getNumbers function cannot use 'return result' because cio.query call is asynchronous and has not set the result variable when getNumbers gets to its end. Hence the callback. Commented Jan 2, 2019 at 7:44
  • I'm grateful for your interest, but how do I transfer the data in the ko variable to the zo variable. currently the ko variable is not undefined but the zo variable is "undefined". Commented Jan 2, 2019 at 7:53

3 Answers 3

2

Here is a quick fix to your code. as being said before, since you do not return this value from the function you have to handle this logic inside the callback. Also, even if you would return a value, ko would still be uninitialized (when you tried to assign it's value to zo), since you use async action to get something from DB, and you do not wait for the data before you assign.

function getNumbers(callback) {
    result = cio.query("SELECT numbers FROM rooms WHERE durum='1'", function (err, result) {
        if (err) throw err;
        callback((result.length > 0) ? result[0].numbers : "");
    });
}

var ko;
var zo;    

getNumbers(function (result) {
  ko = result;
  console.log(result);
  zo = ko;
});

here is an example for a code where zo will still be (given the function is not sync of course) undefined:

function getNumbers(callback) {
    result = cio.query("SELECT numbers FROM rooms WHERE durum='1'", function (err, result) {
        if (err) throw err;
        callback((result.length > 0) ? result[0].numbers : "");
    });
}

var ko;

getNumbers(function (result) {
  ko = result;
  console.log(result);
});
var zo = ko; //Not good!
Sign up to request clarification or add additional context in comments.

2 Comments

I'm very sorry but "zo" comes again undefined, where am i making mistakes. :(
Because you probably console.log before you assign zo, it is only guaranteed that it will be assigned at some time (if there is no error), but not immediately. You should read about asynchronous programming.
2

You can, and your approach would be correct.

The reason ko (and zo, respectively) are undefined is because you are not returning anything from getNumbers, instead, you are using a callback.

Either handle the logic involving the variable inside your callback, or use async and await.

See: Asynchronous JavaScript

Comments

0

You can use this approach:

global.ko; // Declaration of the global variable - undefined
global.ko = 5; // Global variable initialized to value 5.

You can access like this:

var myNumber = global.myNumber;

2 Comments

do NOT use global variables! If you start running you application with multiple processes you will get screwed very badly.
Using global variables is really really bad idea. Also, the real problem here is asynchronous result handling, not how to make a variable globally visible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.