I have the following express node.js app. It's using the 'redis' npm package.
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.
The strange part is that when I run the same redis commands from the command line, the array is populated.
Can anyone tell me what's going on here?
Your code is asynchronous. The callback you pass doesn't get executed until after your console.log
. Try:
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);
});
});