【发布时间】:2022-01-04 12:46:59
【问题描述】:
//local variables
let b1 = []
let b2 = []
let b3 = []
async function start(){
//inserting some data to redis keys a1, a2 and a3
let data = []
for(i=1; i<=3; i++){
data.push(i)
client.set('a'+i, JSON.stringify(data))
}
//now in redis we have a1->[1] , a2->[1,2] and a3->[1,2,3]
//array for promise.all
let arrayX = []
for(i=1; i<=3; i++){
arrayX.push(y(i).then(result => {
eval('b'+i + '=' + result) //updating the value from redis into local variables b1, b2 and b3
console.log(eval('b'+ i)) //here the values of b1, b2 and b3 are displayed
}))
}
//waiting to update b1, b2, b3
await Promise.all(arrayX).then(()=>{
for(i=1; i<=3; i++){
console.log(eval('b'+ i)) //here it is displaying empty array
}
//here I want to call another function where I want to use the values of b1, b2 and b3
})
}
//reading from redis and returning value
function y(i, result){
return new Promise((resolve, reject) => {
client.get('a'+i, async function(err,result){
resolve(result)
})
})
}
start()
使用从 redis 读取的值分配局部变量后,当我稍后尝试访问它时,它们显示为空。但是如果我在分配所有值之后立即显示它。我已经使用 promises 和 promise.all 来进行异步处理,但它仍然不起作用。请帮忙。谢谢。
【问题讨论】:
-
我强烈建议不要使用
eval。请参阅"Variable" variables in JavaScript - 如果您需要大量可以通过编程方式解析的变量,请改用数组或对象。 -
避免以这种方式使用全局变量,如果多个进程使用相同的redis数据库实例运行相同的代码,该软件很可能会失败。从redis中获取你需要的东西,并通过参数在函数中使用值,在不必要的时候避免使用全局变量。如果您需要将未知数量的变量传递给函数,请使用正确的类型(数组、对象或其他)。
-
@briosheje 我用过对象
let js = {} for(i=1; i<=3; i++){ arrayX.push(y(i).then(result => { js[i] = result console.log(js[i]) })) } await Promise.all(arrayX).then(()=>{ console.log(js) })这是输出 [1] [1,2] [1,2,3] { '4': '[1,2,3]' } 这应该是 [1] [1,2] [1,2,3] { '1' : '[1]', '2' : '[1,2]', '3' : '[1 ,2,3]' } 也将 'i' 增加到 4
标签: javascript node.js redis