Redis 流回调无法返回 return 值

Redis stream call back not able to return value

我正在将 redis 流与节点 js 一起使用,我在 returning 异步回调值时遇到问题。请给我建议如何 return 下面的值是我的代码

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"

您不能return回调中的值。

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