【问题标题】:Redis stream call back not able to return valueRedis流回调无法返回值
【发布时间】:2023-04-05 07:53:01
【问题描述】:

我正在使用带有节点 js 的 redis 流,在返回异步回调值时遇到问题。请给我关于如何返回值的建议,下面是我的代码

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"

【问题讨论】:

    标签: node.js redis promise redis-streams


    【解决方案1】:

    你不能从回调中返回值。

    但是,您可以将回调包装在 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);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-04
      • 2021-12-30
      相关资源
      最近更新 更多