0

I have the following code in 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 is an async method. Here are the prints of this function:

"uuid is: 1"
"uuid is: 2"
"uuid INSIDE hget is: 2"
"uuid INSIDE hget is: 2"

I wish to save the context of the uuid inside the hget function, so I will get:

"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)

How can I do that?

MIDE11
  • 3,140
  • 7
  • 31
  • 53

1 Answers1

1

The following code

multiClient.hget(var1, var2, function(err, res1){
   console.log("uuid INSIDE hget is: " + uuid)
}

uuid value will be the value when async operation is completed.

You can solve this using anonymous function executing and copy the value of uuid to some other variable say uuid_temp and use that value as shown below.

(function() {
   var uuid_temp = uuid;
   multiClient.hget(var1, var2, function(err, res1){
      console.log("uuid INSIDE hget is: " + uuid_temp); //note uuid_temp here
   }
}());
rajuGT
  • 6,224
  • 2
  • 26
  • 44