V
V
vetsmen2017-01-14 21:12:10
Redis
vetsmen, 2017-01-14 21:12:10

Why does console.log work but return doesn't?

Guys, why console.log works, but return doesn't? Writes underfind.
Here is the code

var redisClient = require('../lib/redis');

var getChatData = function() {
  redisClient.lrange('messages', 0, 4, function(err, reply) {
    reply.map(function(msg) {
      return JSON.parse(msg);
    })
  });
}

module.exports = getChatData;

and then write in another file
var HomeModel = require('../models/Home');
console.log(HomeModel());

but writes underfind. And if you put console.log instead of return
in the original code , then everything is OK.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Taratin, 2017-01-14
@vetsmen

var redisClient = require('../lib/redis');

var getChatData = function () {
    return new Promise((resolve, reject) => {
        redisClient.lrange('messages', 0, 4, (err, reply) => {
            if (err) {
                reject(err);
            } else {
                resolve(reply.map(msg => JSON.parse(msg)));
            }
        });
    });
}

module.exports = getChatData;

(async () => {
    try {
        const HomeModel = require('../models/Home');
        console.log(await HomeModel());
    } catch (err) {
        console.error(err);
    }
})();

run node.js with harmony flag

A
Anton L, 2017-01-14
@antonecma

Because asynchrony.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question