Redis
 sql >> Base de données >  >> NoSQL >> Redis

Renvoie la liste hgetall de redis dans nodejs

La réponse courte est que vous ne pensez pas de manière asynchrone. Étant donné que vous utilisez des fonctions asynchrones dans votre fonction, votre fonction doit également être asynchrone.

Puisque vous n'avez pas publié le reste de votre code, voici l'idée de base :

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

J'espère que cela aide à clarifier les choses.