【问题标题】:Node_Redis HGET resolving to boolean array when using Promise.all使用 Promise.all 时 Node_Redis HGET 解析为布尔数组
【发布时间】:2017-09-04 17:35:43
【问题描述】:

我一直在研究 redis 并开发一个使用 redis 的小型 web 应用程序,因为它只是数据存储(我知道这不是 redis 的预期目的,但我从学习命令和在 Node 上使用 redis 整体工作中受益. 我正在使用 Node_Redis。

这是我想要完成的(全部在 redis 中): 我正在尝试使用他们的电子邮件检索用户。

问题出在: 我有一个 Promise.all 调用,它接收所有电子邮件(密钥)并将每个电子邮件映射到一个 HGET 命令。当 Promise.all 解析时,我希望它解析为一组用户对象,但最终解析为一组布尔值(即 [true, true, true])。

这是/users的逻辑

router.get("/", (req, res) => {
  client.lrange("emails", 0, 1, (err, reply) => {
    if (err) return console.log(err);
    if (reply) {
      Promise.all(
        reply.map(email => {
          return client.hgetall(email, (err, reply) => {
            if (err) return console.log(err);
            console.log("reply for hgetall", reply); // this prints a user object correct, but Promise.all still resolves to boolean array :(
            return reply;
          });
        })
      )
        .then(replies => {
          // replies = [true, true, true ...]
          res.send(replies);
        })
        .catch(e => console.log(e));
    } else {
      res.send([reply, "reply is null"]);
    }
  });
});

我实际上已经多次使用 Promise.all,当我记录来自 redis 的回复时,它也显示了正确的对象,所以我现在很困惑。如何让 Promise.all 解析为 User 对象数组?

【问题讨论】:

    标签: javascript node.js redis promise node-redis


    【解决方案1】:

    问题是client.hgetall 没有返回承诺。它是异步函数,您通过回调来获得结果。你应该promisify这个函数在Promise.all中使用它:

    ...
    return new Promise((resolve, reject) => {
      client.hgetall(email, (err, reply) => {
        if (err) {
          return reject(err);
        }
        resolve(reply);
      });
    });
    

    您可以手动promisification(如上例所示),也可以使用BluebirdQ 库及其promisifypromisifyAll 方法。

    【讨论】:

      猜你喜欢
      • 2010-09-29
      • 1970-01-01
      • 2013-02-07
      • 1970-01-01
      • 2016-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多