Node.js Redis节点-从哈希中获取-不插入到数组中
我的目标是插入从redis散列中获取的值。我正在为NodeJS使用redis包 我的代码如下:Node.js Redis节点-从哈希中获取-不插入到数组中,node.js,redis,node-redis,Node.js,Redis,Node Redis,我的目标是插入从redis散列中获取的值。我正在为NodeJS使用redis包 我的代码如下: getFromHash(ids) { const resultArray = []; ids.forEach((id) => { common.redisMaster.hget('mykey', id, (err, res) => { resultArray.push(res); }); }); console.log
getFromHash(ids) {
const resultArray = [];
ids.forEach((id) => {
common.redisMaster.hget('mykey', id, (err, res) => {
resultArray.push(res);
});
});
console.log(resultArray);
},
函数末尾记录的数组为空,res不为空。我能做些什么来填充这个数组 您需要使用一些控制流,无论是库还是承诺()
当redis调用返回结果时,将您的
console.log
放在回调中。然后您将看到更多打印输出。也可以为您的.forEach
使用一种控制流模式,因为它当前是同步的。如果您将代码修改为类似的内容,它将很好地工作:
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.all
您将在Node中经常看到这种行为,请记住,它几乎对所有i/o都使用异步调用。当您来自一种大多数函数调用都是同步的语言时,您经常会被这种问题绊倒