我正在尝试返回一个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;
答案 0 :(得分: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
});
});
});
希望这有助于澄清事情。
答案 1 :(得分:0)
我还遇到了类似的问题,其中我需要hgetall
的结果返回调用它的函数。这就是我如何使其最终发挥作用的方法。
export const test = async (hashId) => {
// reachedLimit will have value after the hgetall result on the `monitorLimit` function
const reachedLimit = await monitorLimit(hashId);
}
export const monitorLimit = (hashId) => {
let reachedLimit = false;
let attempts = 0;
return new Promise((resolve, reject) => redisDB.hgetall(hashId, (err, result) => {
if (err) {
// TODO reject logic here...
}
if (result) {
attempts = Number(result.tries);
if (attempts === 3) {
reachedLimit = true;
resolve({ reachedLimit });
}
}
attempts += 1;
redisDB.hmset(hashId, ['tries', attempts], (createErr) => {
if (createErr) {
// TODO reject logic here...
}
});
// expire in 3 minutes
redisDB.expire(hashId, 180);
resolve({ reachedLimit });
}));
};
答案 2 :(得分:0)
处理hgetall返回值的唯一方法是Promises。
获取所有功能:
async hashget(tag) {
return new Promise((resolve, reject) => {
redis.createClient({ port: portnumber, host: config.redis.host
}).hgetall(tag, (err, object) => {
if (err) {
reject(err);
} else {
resolve(Object.keys(object));
}
});
});
}
并通过
const result = await this.redis.hashget('asize').then((result) => {
return result;
});
return result;
答案 3 :(得分:0)
我针对此错误的解决方案 SyntaxError:JSON中位置1处的意外令牌o
res.send(Object.values(JSON.parse(JSON.stringify(object))))