2014-03-01 126 views
1

我試圖返回一個json對象,以便在頁面呈現到填充列表之前我可以將其傳回。我的問題是,我無法弄清楚如何從hgetall回調函數中傳出對象數據。這裏是我的例子,對我缺少的東西發表評論:從nodejs的redis中返回hgetall列表

var redis = require("redis"), 
    client = redis.createClient(); 

function createMobs() { 

    var mobObject = { 
     name: "Globlin", 
     hp: 12, 
     level: 1 
    }; 
    client.hmset("monsterlist", "mobs", JSON.stringify(mobObject)); 

    var myMobs = function(object) { 
     return object; 
    }; 

    var getMobs = function(callback) { 
     client.hgetall("monsterlist", function(err, object) { 
     callback(object); 
     });  
    }; 

    // This is returning undefined instead of my mob 
    console.log("mobs: ", getMobs(myMobs)); 

    // Goal is to return moblist 
    // return getMobs(myMobs); 

} 

exports.createMobs = createMobs; 

回答

4

簡短的答案是,你不是在異步思考。由於您在函數中使用異步函數,因此您的函數也必須是異步的。

既然你沒有張貼你的代碼的其餘部分,這裏的基本思想是:

var client = require('redis').createClient(); 

function createMobs(callback) { 
    var mobObject = { name: 'Goblin' }; 

    client.hmset('monsterlist', 'mobs', JSON.stringify(mobObject), function(err) { 
     // Now that we're in here, assuming no error, the set has went through. 

     client.hgetall('monsterlist', function(err, object) { 
      // We've got our object! 

      callback(object); 
     }); 

     // There is no way to run code right here and have it access the object variable, as it would run right away, and redis hasn't had time to send you the data yet. Your myMobs function wouldn't work either, because it is returning a totally different function. 
    }); 
}; 

app.get('/create', function(req, res) { 
    createMobs(function(object) { 
     res.render('mobs.jade', { 
      mobs: object 
     }); 
    }); 
}); 

希望幫助清楚的事情了。

+0

謝謝,它的確如此,我試圖只返回對象,這是我的問題,而不是在完成操作時做某件事。 – Organiccat