2015-04-03 107 views
0

我試圖在NodeJS中使用開放圖插件來獲取藤的預覽圖像。 OG結果是正確的,但我不能從og回調中訪問result [i] - 變量未定義。我如何訪問OG回調中的結果[i]?JavaScript:在回調中訪問變量

Thing.find(function(err, result) { 
     for (var i = 0; i < result.length; i++) { 
      if (result[i].attachment) { 
       if (result[i].attachment.embed_type == 'vine') { 
        og(result[i].attachment.embed_url, function(err, meta) { 
         result[i].attachment.preview_image = meta.image; 
         result[i].save(); 
        }); 
       } 
      } 
     } 
    }); 
+0

的可能重複的[JavaScript的閉合環內 - 簡單實用示例](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Zirak 2015-04-03 23:39:03

回答

1

您需要關閉,i不斷變化,因爲og是異步

Thing.find(function(err, result) { 
    for (var i = 0; i < result.length; i++) { 
     if (result[i].attachment && 
      result[i].attachment.embed_type == 'vine') 
     { 
      (function(res) { 
       og(res.attachment.embed_url, function(err, meta) { 
        res.attachment.preview_image = meta.image; 
        res.save(); 
       }); 
      }(result[i])); 
     } 
    } 
}); 
+0

這應該是爲了清晰起見,在「for」循環之外完成。 IIFE不是去這裏的路。 – Sethen 2015-04-03 16:56:39

+0

在我看來,一個IIFE是去這裏的方式,但任何功能都可以做 – adeneo 2015-04-03 16:57:31

+0

它不是可擴展的,只是使事情進一步複雜化。這是不正確的,並且無助於此代碼的清晰度和可重用性。 – Sethen 2015-04-03 16:58:07

0

JS does not have block scope

有一些方法來解決這個問題,例如創建一個函數。並且,爲了使它更加清晰和易於測試,我也將所有result[n]邏輯放在其他函數中。

var process = function(resultItem) { 
    if (resultItem.attachment && if (resultItem.attachment.embed_type == 'vine')) { 
    og(resultItem.attachment.embed_url, function(err, meta) { 
     resultItem.attachment.preview_image = meta.image; 
     resultItem.save(); 
    }); 
    } 
}; 

Thing.find(function(err, result) { 
    for (var i = 0; i < result.length; i++) { 
    process(result[i]); 
    } 
});