我试图让 client.get 返回回复值,以便它可以在全局范围内使用。它一直显示未定义。有任何建议
var redis = require("redis");
var websocket= require("websocket");
var valuewanted;
websocket.on('message', function(data) {
if (data.type == "purchase" && data.price > 0) {
console.log("==========================================================");
console.log(data );
console.log("==========================================================");
client.get(p1, function(err, reply) {
var valuewanted = reply;
console.log(reply);
});
});
console.log 记录该值,但如果我尝试记录 valuewanted 它不起作用。
最佳答案
将 var
放入 client.get 函数中:
client.get(p1, function(err, reply) {
// valuewanted already defined above
valuewanted = reply;
console.log(reply);
});
如果您在函数中使用 var,它将对该函数产生作用域限制。
来自mozilla :
The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global.
在这种情况下,在该函数内使用 var
会在该函数内重新定义它,并且其作用域变为“封闭函数”。希望这会有所帮助。
关于javascript - 从回调函数内部返回 javascript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47253033/