for循环中的异步chrome方法

时间:2013-03-24 11:58:03

标签: javascript google-chrome-extension bookmarks

对于每个变量i,代码下面应该遍历每个书签节点并比较网址,无论它是否存在。

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

因为该方法是异步的,所以我得到最后一条消息并且书签遍历不会发生。 任何帮助将不胜感激。

谢谢!!

1 个答案:

答案 0 :(得分: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变量?