0

I use node_redis module for caching comments and need get this comments when new will approved.

Function that get comments from Redis store below:

var client = redis.createClient();

........

function getComments() {
    client.keys("*", function (err, replies) {
        var comments = [];
        if (err) throw new Error('Redis error');
        //console.log(replies.length + " replies:");

        replies.forEach(function (reply, i) {
            client.get(reply, function (err, value) {
                if (err) throw new Error('Redis error');
                //console.log(i+"    " + reply + ": " + value);
                comments[i] = value;
                console.log(comments);  //comments - not empty here
            });
        });
        console.log(comments); //comments is empty here
        client.quit();
    });
}

Problem desribed in comments. When forEach finished it works, comments array is empty. How can I add callback for foreach to save scope with comments to get then data from this array ?

LIAL
  • 1,624
  • 4
  • 24
  • 30
  • Same idea as the duplicate: `client.get` is an asynchronous function. The `console.log` at the bottom gets executed before the callback in that `get` is. – Cerbrus Jan 13 '15 at 15:39
  • That question you indicate me - has now the answer I asked. I would like to know how add callback function for forEach (to intercept the moment when this loop will finished his work) or how wrap this loop to closure to get scope with comments array. – LIAL Jan 13 '15 at 15:50

0 Answers0