0

I have a class with two methods

class User {
    fetchAll(project) {
        redisClient.keys(
            'user:' + project + '*',
            function (error, response) {
                if (error) {
                    pmx.notify('user:all:fetch_failed', {error: error});
                    return false;
                }

                return response;
            }
        );
    }

    updateLastDate(project, id) {
        let time = new Date().toTimeString().slice(0, 8);
        redisClient.hset(['user:' + project + ':' + id, 'lastDate', time]);
    }
}

updateLastDate works fine, but fetchAll returns undefined when i try to get data like this

let user = new User();
let users = user.fetchAll('localhost');
console.log(users);

Why?

p.s. Redis lib is https://www.npmjs.com/package/redis, and node.js is 6.9.0

Solution:

fetchAll(project, callback) {
    redisClient.keys(
        'user:' + project + '*',
        function (error, response) {
            if (error) {
                return callback({error: error);
            }

            return callback(null, response);
        }
    );
}
Itsmeromka
  • 3,621
  • 9
  • 46
  • 79
  • 1
    isn't it return inside callback? – Mritunjay Nov 25 '16 at 12:02
  • 1
    From your linked documentation: *"Note that the API is entirely asynchronous."* That means `fetchAll` **cannot** return the result. And even if `redisClient.keys` called its callback synchronously, your `return response` is inside the callback, and so returns `response` from the callback, not from `fetchAll`. But that's a side point, because `fetchAll` cannot return the information you want it to return. – T.J. Crowder Nov 25 '16 at 12:02
  • 1
    duplicate: http://stackoverflow.com/questions/19739755/nodejs-callbacks-simple-example – iKoala Nov 25 '16 at 12:03
  • So it must be like `fetchAll(project, callback) { ...` ? – Itsmeromka Nov 25 '16 at 12:05
  • 1
    yes, you have to use either `callback` or `Promise` – iKoala Nov 25 '16 at 12:06

0 Answers0