2016-08-22 7 views
0

私はJavaScriptで次のコードを持っている:の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) 

はどのように私はそれを行うことができますか?

答えて

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 
    } 
}());