0

So I am trying to create a bunch of tabs from a list of tabs in a list names groups like this..

console.log("groups.length: " + groups.length);
// loop through groups
    for (var i = 0; i < groups.length; i++) {
        // create the new tab
        console.log("for loop ran: " + i);

        // cannot use i in here because async
        chrome.tabs.create({
            windowId: win.id,
            index: i,
            url: groups[i].urls[0]
        }, function(tab){
            console.log("i: " + i);
            groups[i].tabId = tab.id;  // this is not working right!!!
        });
    }

So in the terminal I get..

groups.length: 2
popup.js:87 for loop ran: 0
popup.js:87 for loop ran: 1
popup.js:95 i: 2
popup.js:95 i: 2

Can someone explain to me what is going on here. I thought that even though the task is async it should still input the value of i as it was when the call was first made. Also why would line 95 ever show i = 2? How could i ever be greater than 1? I'm really confused, thanks kind internet programmers.

Shawn Volpe
  • 337
  • 1
  • 4
  • 10
  • 1
    The explanation part is documented in an excellent answer here: [Asynchronous code reference](http://stackoverflow.com/a/23667087/3959875). – wOxxOm Sep 28 '15 at 21:31

2 Answers2

0
groups.forEach(function (group, i) {
    chrome.tabs.create({
        windowId: win.id,
        index: i,
        url: group.urls[0]
    }, function(tab){
        group.tabId = tab.id;
    });
});
artit91
  • 83
  • 7
0

After your code ran, i is 2 because in a for loop, the increment expression i++ is executed after each loop cycle, and then the condition is checked to determine. So the code executes as follows: first_cycle -> increment (i is 1 now) -> check_condition (true) -> second_cycle -> increment (i is 2 now) -> check_condition (false) -> abort loop

Change your callback function to:

function(tab) {
    console.log("index" + tab.index);
    groups[tab.index].tabId = tab.id;
}

because this way, code within the callback function does not use the variable i of the outer function (more about lexical scope and closures here

... or use artit91's solution.

the_tiger
  • 346
  • 1
  • 9