1

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"
4

1 回答 1

2

您不能从回调中返回值。

但是,您可以将回调包装在 Promises 中并将其作为 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);

于 2021-07-30T09:11:46.993 回答