2017-09-04 174 views
1

时,我已经挖成的Redis和使用Redis的,因为它是唯一的数据存储一个微小的web应用程序的工作分解到布尔数组(我知道这不是Redis的的预期目的,但我从受益学习的命令,只是整体上节点的Redis我使用Node_Redis工作Node_Redis HGET使用Promise.all

这是我想要完成的(所有的Redis)什么:。 我尝试使用他们的电子邮件检索用户

这里的问题: 我有一个Promise.all调用带所有电子邮件(密钥)和映射每个去一个HGET命令。当Promise.all解析我期望它与用户对象的数组来解决,但它最终解析为布尔值的阵列(即[真,真实,真])。

这里是我实际使用Promise.all大量的时间/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"]); 
    } 
    }); 
}); 

的逻辑,当我登录从Redis的回复,它显示了正确的对象太多,所以我很困惑在这一点上。我怎样才能得到Promise.all解析为用户对象的数组?

回答

2

的问题是,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方法。