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);
});
});
.send()
uses text/html and .json()
uses json headers. How important that is depends on your use case I suppose - davin 2012-04-04 23:03
.json()
seems like the more natural fit. Either way you can only execute them at the end of the callback. Take care - davin 2012-04-04 23:07
res.send(data)
and i tried putting it inside the callback. But since that was wrong too i didn't see that was the solution. thank you - Matt Phillips 2012-04-04 22:51