更新代码:我,我是 Javascript 编程的新手,在尝试从方法分配新变量时得到一个 undefined variable 。
我正在使用 node.js 并使用“客户端变量”中的 redis-client 创建一个 redis 服务器。
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);
当我在回调函数内调用 console.log 时,它返回正确的值,但是当我在回调函数外调用 console.log 时,它返回“undefined”。我正在尝试将回调函数内的值分配给全局变量 numberPosts。
非常感谢任何帮助,谢谢。
马特
最佳答案
我相信这会奏效:
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 调用完成之前不可用,因此您的原始代码无法工作。没有直接返回值存储。
您可以将计时器设置为一些合理的响应时间,然后让代码使用其中的全局变量。
编辑二:为了在完成后再次调用方法,有这样的代码:
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 或您传递了一些硬编码限制以防止无限循环。
关于javascript - 在 Javascript 中获取 undefined variable ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5004335/