开发者

Getting Undefined Variable in Javascript

开发者 https://www.devze.com 2023-02-10 08:53 出处:网络
UPDATED CODE: i, I\'m new to Javascript programming and getting an undefi开发者_StackOverflow社区ned variable when trying to assign a new variable from a method.

UPDATED CODE: i, I'm new to Javascript programming and getting an undefi开发者_StackOverflow社区ned 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


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.


Try this instead to see errors:

var redis = require("redis"); 

client = redis.createClient(); 

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

//note the error logging
var numberPosts = client.get("global:nextPostId", function (error, response) {
  if (error) {
    console.log("async: " + error);
  } else {
    console.log("programming: " + response);
  }
});

console.log("is lotsa fun: " + numberPosts);

As Shadow Wizard has pointed out you are trying to use numberPosts before there is something in it, as client.get() hasn't returned anything.

Read this to get a handle on node.js flow:

http://www.scribd.com/doc/40366684/Nodejs-Controlling-Flow


I was facing the the same issue when I applied the MVC framework. To solve the problem, I employed the render function.

In the posts Model

exports.get = function(id,render) {
    client.incr('post:id:'+id, function(err, reply) {
    render(reply);
    });
};

In the posts Controller

exports.get = function(req, res) {
    posts.get('001', function (data){res.render('index',{post:data});});

};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号