Search code examples
node.jsredispromiseredis-streams

Redis stream call back not able to return value


I am using redis stream with node js, I am facing issue when returning the async callback value. please give me suggestion on how I can return value below is my code

const redis = require('redis')
const redisClient = redis.createClient({
  host: 127.0.0.1,
  port: 6379
})

let array = []
 let userCreated = await redisClient.xread(
    'BLOCK',
    0,
    'STREAMS',
    'user:created',
    '$',
    (err, str) => {
      if (err) return console.error('Error reading from stream:', err)
      str[0][1].forEach(message => {
        id = message[0]
        console.log(message[1])
        return array.push(message[1]) // I get value here
      })
      return array 
    }
  )

console.log(userCreated) "undefiend"

Solution

  • You can not return a value from the callback.

    However, you can wrap the callback in Promises and return it as a promise.

    const redis = require("redis");
    const redisClient = redis.createClient({
      host: "127.0.0.1",
      port: 6379,
    });
    
    async function asyncRedis() {
      try {
        const userCreated = await asyncXread();
        return userCreated;
      } catch (err) {
        console.log(err);
        throw new Error(err);
      }
    }
    
    function asyncXread() {
      return new Promise((resolve, reject) => {
        redisClient.xread(
          "BLOCK",
          0,
          "STREAMS",
          "user:created",
          "$",
          (err, str) => {
            if (err) {
              console.error("Error reading from stream:", err);
              reject(err);
            }
            const array = [];
            str[0][1].forEach(message => {
              id = message[0];
              console.log(message[1]); // I get value here
              array.push(message[1]);
            });
            resolve(array);
          }
        );
      });
    }
    
    asyncRedis().then(console.log).catch(console.log);