我在JavaScript中有以下代码:
for (var i = 0; i< uuids.length; i++){
var attr = uuids[i]
var uuid = attr["uuid"];
console.log("uuid is: " + uuid)
multiClient.hget(var1, var2, function(err, res1){
console.log("uuid INSIDE hget is: " + uuid)
}
}
hget
是一种异步方法。以下是此功能的打印件:
"uuid is: 1"
"uuid is: 2"
"uuid INSIDE hget is: 2"
"uuid INSIDE hget is: 2"
我希望在hget函数中保存uuid的上下文,所以我会得到:
"uuid is: 1"
"uuid is: 2"
"uuid INSIDE hget is: 1" (where all the context before the loop has saved for this uuid)
"uuid INSIDE hget is: 2" (where all the context before the loop has saved for this uuid)
我该怎么做?
答案 0 :(得分:1)
以下代码
multiClient.hget(var1, var2, function(err, res1){
console.log("uuid INSIDE hget is: " + uuid)
}
uuid
值将是异步操作完成时的值。
您可以使用匿名函数执行此操作并将uuid
的值复制到其他变量uuid_temp
并使用该值,如下所示。
(function() {
var uuid_temp = uuid;
multiClient.hget(var1, var2, function(err, res1){
console.log("uuid INSIDE hget is: " + uuid_temp); //note uuid_temp here
}
}());