【问题标题】:Redis Node - Get from hash - Not inserting into arrayRedis节点 - 从哈希中获取 - 不插入数组
【发布时间】:2018-08-03 08:48:11
【问题描述】:

我的目标是插入从 redis 哈希中获得的值。我正在使用 node js 的 redis 包。

我的代码如下:

getFromHash(ids) {
    const resultArray = [];
    ids.forEach((id) => {
      common.redisMaster.hget('mykey', id, (err, res) => {
        resultArray.push(res);
      });
    });
    console.log(resultArray);
  },

函数末尾记录的数组为空,res不为空。请问我能做些什么来填充这个数组?

【问题讨论】:

    标签: node.js redis node-redis


    【解决方案1】:

    您需要使用一些控制流,async 库或 Promises (as described in reds docs)

    当结果从 redis 调用返回时,将您的 console.log 放入回调中。然后你会看到更多的打印输出。也为您的.forEach 使用一种控制流模式,因为它当前是同步的。

    【讨论】:

      【解决方案2】:

      如果你把你的代码修改成这样,它会很好地工作:

      var getFromHash = function getFromHash(ids) {
          const resultArray = [];
          ids.forEach((id) => {
              common.redisMaster.hget('mykey', id, (err, res) => {
                  resultArray.push(res);
                  if (resultArray.length === ids.length) {
                      // All done.
                      console.log('getFromHash complete: ', resultArray);
                  }
              });
          });
      };
      

      在您的原始代码中,您在任何 hget 调用返回之前打印结果数组。

      另一种方法是创建一个 Promise 数组,然后对其执行 Promise.all。

      您会在 Node 中经常看到这种行为,记住它对几乎所有 i/o 都使用异步调用。当您来自大多数函数调用是同步的语言时,您会经常遇到此类问题!

      【讨论】:

        猜你喜欢
        • 2015-11-08
        • 2014-06-28
        • 2012-08-17
        • 2013-06-17
        • 1970-01-01
        • 2021-07-16
        • 1970-01-01
        • 1970-01-01
        • 2015-12-10
        相关资源
        最近更新 更多