1

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. browser

The strange part is that when I run the same redis commands from the command line, the array is populated.

enter image description here

Can anyone tell me what's going on here?

1 Answer 1

10

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);
    });
});
Sign up to request clarification or add additional context in comments.

6 Comments

Doh! I figured it was something like that. Originally i was just doing 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!
@MattPhillips, that first method should've worked just fine!?
so you can do res.send and pass json and it will set the headers properly? I swear it wasn't working.
@MattPhillips, depends what you mean by "properly". You can set the headers either way, although presumably (need to check) .send() uses text/html and .json() uses json headers. How important that is depends on your use case I suppose.
well when the url i'm "GET"-ing in the client code expects application/json. So I'd say pretty important. That way I don't have to parse it back out on the client side.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.