0

Using node.js, I am connecting to my redis database and returning the values into an array. However, in order to return the values, I must use a callback function to get them out of the scope. I have seen many examples on SO of callback functions in action, and mine works just like all the others I have seen, however, when I call the function as an option in res.render, it tries to return the parent function rather than the callback. How do I return the callback function's value to the players: option?

Parent Function

function openPlayers(callback) {
  var players = [];
  db.hgetall("players", function(err, objs) {
    // Objects of Response
    for (var k in objs) {
      // Items are the individual key-value object
      var newPlayer = {};
      var items = JSON.parse(objs[k]);
      for (var x in items) {
        // x is the key for each object
        newPlayer[x] = items[x];
      }
      players.push(newPlayer);
    }
    callback(players);
  });
}

Location of Callback Function

exports.newPlayer = function(req, res) {
  res.render('newPlayer', {
    title: 'New Player',
    players: (openPlayers(function(ps) { //callback function
              return(ps);
            }))
  });
};
1
  • 3
    Returning from asynchronous callback is useless. You have to invert the logic, and call res.render from your callback. Commented Aug 25, 2013 at 20:59

1 Answer 1

4

Well, you can't since openPlayers is async and doesn't return any value, that's why it takes a callback. What you could do is something like this however:

exports.newPlayer = function(req, res) {

    openPlayers(function (ps) {
        res.render('newPlayer', {
            title: 'New Player',
            players: ps
        });
    });
};
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, ok... this async stuff is ridiculous. Thanks so much for the great answer!

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.