Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Undefined Variable in Javascript

UPDATED CODE: i, I'm new to Javascript programming and getting an undefined variable when trying to assign a new variable from a method.

I'm using node.js and creating a redis server using the redis-client in the "client variable".

var redis = require("redis");
var client = redis.createClient();

client.on("error", function (err) {
console.log("Error " + err); });

var numberPosts;

client.get("global:nextPostId", function(err, replies) {
  numberPosts = replies;
  console.log(numberPosts);
});

console.log(numberPosts);

When I call console.log inside the call back function it returns the proper value, however when I call the console.log outside of the callback function it returns "undefined". I'm trying to assign the value that is inside the callback function to the global variable numberPosts.

Any help is much appreciated, thanks.

Matt

like image 803
Matikus1trillion Avatar asked May 09 '26 16:05

Matikus1trillion


1 Answers

I believe this will work:

client.get("global:nextPostId", function (err, reply) {
    console.log("Number of posts: " + reply.toString());
})

The AJAX call is asynchronous so it doesn't have return value.. instead you have to use callback function and only there you have the value returned by the server method.

Edit: to assign the return value to global variable, first declare global variable:

var _numOfPosts = "";

Then:

client.get("global:nextPostId", function (err, reply) {
     _numOfPosts = reply.toString());
})

However, the value won't be available until the AJAX call is finished so your original code can't work. There is not direct return value to store.

You can set timer to some reasonable response time, then have the code using the global variable in there.

Edit II: in order to call the method again once it's finished, have such code:

var _nextPostCallCount = 0;
function GetNextPost() {
   //debug
   console.log("GetNextPost called already " + _nextPostCallCount  + " times");

   //sanity check:
   if (_nextPostCallCount  > 1000) {
      console.log("too many times, aborting");
      return;
   }

   //invoke method:
   client.get("global:nextPostId", function(err, replies) {
      numberPosts = parseInt(replies.toString(), 10);
      console.log("num of replies #" + (_nextPostCallCount + 1) + ": " + numberPosts);

      //stop condition here.... for example if replies are 0
      if (!isNaN(numberPosts) && numberPosts > 0)
         GetNextPost();
   });

   //add to counter:
   _nextPostCallCount++;
}
GetNextPost();

This will call the method over and over until the result is 0 or you pass some hard coded limit to prevent endless loop.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!