Getting Undefined Variable in Javascript

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

I use node.js and create a redis server using redis-client in a "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 callback function, it returns the correct value, however, when I call console.log outside the callback function, it returns "undefined". I am trying to assign a value that is inside a callback function to the global variable numberPosts.

Any help is greatly appreciated, thanks.

Matt

+3
source share
3 answers

I believe this will work:

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

AJAX- , . , , .

: , :

var _numOfPosts = "";

:

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

, AJAX , . .

, .

Edit II: , :

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();

, 0 , .

+4

:

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);

Shadow Wizard , numberPosts, - , client.get() .

, node.js:

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

0

I encountered the same problem when I applied the MVC environment. To solve this problem, I used the render function.

In Model Posts

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

In Controller columns

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

};
0
source

Source: https://habr.com/ru/post/1792235/


All Articles