从nodejs的redis中返回hgetall列表

我试图返回一个json对象,以便我们可以在页面呈现之前将其传回,以填充列表。 我的问题是我无法弄清楚如何从hgetallcallback函数中传出对象数据。 这里是我的例子与我失踪的评论:

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; 

简短的答案是,你不是在asynchronous思考。 由于您在函数中使用asynchronous函数,因此您的函数也必须是asynchronous的。

由于您没有发布代码的其余部分,因此以下是基本思路:

 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 }); }); }); 

希望这有助于清理事情。