2013-03-24 51 views
0

對於每個變量i,下面的代碼應該遍歷每個書籤節點並比較url是否存在。循環中的異步鑲嵌方​​法

for(i=0;i<arg1;i++){ 
    chrome.bookmarks.getChildren(Traverse[i], function(child){  //to fetch the child nodes 
     Loc =child.length; 
     alert(Loc); // This message to appear first 
     if(Loc != 0){ 
      child.forEach(function(book) { 
       if (book.url == urL){ 
        alert("Bookmark already exist"); 
        element = "init"; 
       } 
      }); 
     } 
    }); 
alert("message to be printed last"); 
} 

由於該方法是異步的,我得到的最後一條消息和書籤遍歷不會發生。 任何幫助將不勝感激。

謝謝!

回答

0

你可能需要一個封閉:

for(i=0;i<arg1;i++){ 
    (function(my_i) { 
     chrome.bookmarks.getChildren(Traverse[my_i], function(child){ 
      Loc =child.length; 
      alert(Loc); 
      if(Loc != 0){ 
       child.forEach(function(book) { 
        if (book.url == urL){ 
         alert("Bookmark already exist"); 
         element = "init"; 
        } 
       }); 
      } 
     }); 
    })(i); 
    alert("message to be printed last"); 
} 

我猜你意識到你是在循環內每個迭代覆蓋兩個Locelement變量?

+0

謝謝Adeneo!上面的代碼很好。我正在測試它。 另外一個查詢,當我點擊書籤時如何退出場景,即如何退出循環,因爲break語句不起作用。 – 2013-03-24 13:08:34