Q:

asynchronous chrome method inside for loop

for every variable i, below code should traverse thro' each bookmark node and compares the url, whether it exist or not.
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");
}

since the method is asynchronous, i'm getting the last message and bookmark traversing doesn't happens.
Any help would be much appreciated.
Thanks !! 

A:

You probably need a closure:
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");
}

I'm guessing you're aware that you are overwriting both the Loc and the element variables on each iteration inside the loop ?

