2

I have a Redis server with 2 keys. I'm trying to fetch both the keys and combine them into 1 response. I'm using node-redis.

My code:

var res = [];
RedisClient.keys('*', async function (err, keys) {
  if (err) return console.log(err);
  if (keys) {
    keys.forEach((key) => {
      RedisClient.get(key, (err, data) => {
        if (err) throw err;

        res.push(data);
      });
    });
    return res.status(200).send(JSON.parse(res));
  }
});

When I run this I get: UnhandledPromiseRejectionWarning: SyntaxError: Unexpected end of JSON input [0] at JSON.parse (<anonymous>). If I remove JSON.parse I get a response but it's an empty array.

I created my answer off of this solution

user
  • 1,022
  • 2
  • 8
  • 30
  • You need to use promise to wait for the `RedisClient.get()` to return the data before you can send a response. – Rifat Bin Reza Mar 01 '21 at 03:50
  • Maybe something like `const result = await Promise.all(keys.map(key => RedisClient.get(key).then(data => JSON.parse(data));` otherwise you’d manually create a promise from each get(), resolve the data, and promise all. – Alexander Staroselsky Mar 01 '21 at 03:56
  • I used your suggestion. I tried this, however this only returns 2 arrays of true. What am I doing wrong? `await Promise.all(keys.map((key)=>RedisClient.get(key))).then((values) => {res.send(values);});` – user Mar 01 '21 at 17:23

0 Answers0