javascript nodejs express 应用程序不会返回 json 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10020315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
nodejs express application won't return json array
提问by Matt Phillips
I have the following express node.js app. It's using the 'redis' npm package.
我有以下 Express node.js 应用程序。它使用的是“redis”npm 包。
app.get("/test",function(req,res){
var data = [];
client.HGETALL("receipts",function(err,obj){
for(var id in obj){
data.push(JSON.parse(obj[id]));
}
});
console.log(data);
res.json(data);
});
app.listen(3000);
The code run's without errors; however, the data
variable is []
when it's returned to the browser.
代码运行没有错误;但是,data
变量是[]
返回到浏览器的时间。
The strange part is that when I run the same redis commands from the command line, the array is populated.
奇怪的是,当我从命令行运行相同的 redis 命令时,数组被填充。
Can anyone tell me what's going on here?
谁能告诉我这里发生了什么?
回答by davin
Your code is asynchronous. The callback you pass doesn't get executed until afteryour console.log
. Try:
您的代码是异步的。你传递回调没有得到执行,直到后您的console.log
。尝试:
app.get("/test",function(req,res){
var data = [];
client.HGETALL("receipts",function(err,obj){
for(var id in obj){
data.push(JSON.parse(obj[id]));
}
console.log(data);
res.json(data);
});
});