我试图返回一个json对象,以便可以在呈现页面以填充列表之前将其传递回来。我的问题是我不知道如何从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;
ZachRabbit.. 5
简短的答案是您不是在异步思考。因为您在函数中使用异步函数,所以您的函数也必须是异步的。
由于您没有发布其余代码,因此有以下基本思想:
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 }); }); });
希望这有助于清理问题。