I'm having this issue where I want to get all of the keys in my redis' cache, store them in an array and send that array with express to the user. The problem is that I receive an empty array in the response with no objects in it. I have tried using for (const x of ...) {...}
but that didn't work either. Tried searching up for answers on the internet , still nothing. Can you explain why is this happening and also here's my code.
exports.fetch = (_req, res) => {
redis.keys("*", (err, reply) => {
if (err) return res.json({ error: err });
else {
const rooms = [];
reply.map((key) => {
redis.get(key, (err, room) => {
if (err) console.error(err);
else rooms.push(room);
});
});
return res.json(rooms);
}
});
};
Update
Thanks everyone for responding.
As @boolfalse suggested, I used async
module and it worked!
Here's my updated code
exports.fetch = (_req, res) => {
redis.keys("*", (err, reply) => {
if (err) return res.json({ error: err });
else {
async.map(
reply,
(key, cb) => {
redis.get(key, (err, room) => {
if (err) return cb(err);
else return cb(null, room);
});
},
(err, results) => {
if (err) return res.json({ error: err });
else return res.json(results);
}
);
}
});
};
But I kinda don't understand why and how it worked...
Thanks anyways for doing research and providing your time