Take the 2-minute tour ×

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];

Location of Callback Function

exports.newPlayer = function(req, res) {
  res.render('newPlayer', {
    title: 'New Player',
    players: (openPlayers(function(ps) { //callback function
share|improve this question
Returning from asynchronous callback is useless. You have to invert the logic, and call res.render from your callback. –  bfavaretto Aug 25 '13 at 20:59

1 Answer 1

up vote 4 down vote accepted

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
share|improve this answer
Ok, ok... this async stuff is ridiculous. Thanks so much for the great answer! –  derek_duncan Aug 25 '13 at 21:11

Your Answer


