从 nodejs 中的 redis 返回 hgetall 列表 [英] Return hgetall list from redis in nodejs

查看:163
本文介绍了从 nodejs 中的 redis 返回 hgetall 列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试返回一个 json 对象,以便我可以在呈现页面以填充列表之前将其传回.我的问题是我不知道如何从 hgetall 回调函数中传递对象数据.这是我的示例,其中包含对我缺少的内容的评论:

I'm trying to return a json object so that I can pass it back before a page is rendered to populate a list. My problem is that I can't figure out how to pass the object data out from the hgetall callback function. Here is my example with comments on what I'm missing:

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;

推荐答案

简而言之,您不是在异步思考.因为您在函数中使用了异步函数,所以您的函数也必须是异步的.

The short answer is that you're not thinking asynchronously. Because you're using asynchronous functions in your function, your function must also be asynchronous.

由于您没有发布其余代码,因此基本思路如下:

Since you didn't post the rest of your code, here's the basic idea:

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

希望这有助于澄清问题.

Hopefully that helps clear things up.

这篇关于从 nodejs 中的 redis 返回 hgetall 列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆