2013-03-24 85 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