I2mNew
I2mNew

Reputation: 173

JavaScript doesn't wait for loop

I'm making a Google Chrome extension. I'm trying to open new tabs and group them. I have urls as an array. But chrome.tabs.group function doesn't wait until all tabs open.

var ourTabIds = []
for(const url of urls) {
    chrome.tabs.create({active: false, url : url},tab => {
         ourTabIds.push(tab.id)
    })
}
chrome.tabs.group({tabIds : ourTabIds}, groupId => {console.log(groupId)})

The group function works when the ourTabIds is still empty. So it gives errors.

Why it doesn't wait? How can I fix that?

Upvotes: 1

Views: 123

Answers (3)

Jamiec
Jamiec

Reputation: 136174

You could promisify chrome.tabs and then use Promise.all

function createTab(input){
   return new Promise(resolve => {
     chrome.tabs.create(input,tab => resolve(tab))
   });
}

and then you code becomes

(async function doIt(){
   var tabs = await Promise.all(urls.map(url => createTab({active: false, url : url})));

   chrome.tabs.group({tabIds : tabs.map(t => t.id)}, groupId => {console.log(groupId)})

})()

Upvotes: 1

iwaduarte
iwaduarte

Reputation: 1698

The function chrome.tabs.create() uses a callback as parameter. You should either convert that to Promises and finish it all with .then() or check if it is the last url (changing from of to in)

var ourTabIds = []
for(const index in urls) {
    chrome.tabs.create({active: false, url : urls[index]}, tab => {
         ourTabIds.push(tab.id)
         if (index === urls.length - 1 ) { // last url 
    //call when EVERYTHING has been pushed by the callback                 
chrome.tabs.group({tabIds : ourTabIds}, groupId => {console.log(groupId)}) 
             }
        })
    }

Upvotes: 0

Nicolas I
Nicolas I

Reputation: 234

var ourTabIds = [];
var countTabs = 0;
    for(const url of urls) {
            chrome.tabs.create({active: false, url : url},tab => {
                 ourTabIds.push(tab.id)
            countTabs++;
           if (countTabs==urls.length){
              chrome.tabs.group({tabIds : ourTabIds}, groupId => {console.log(groupId)})
            }
          })
        }
        

Upvotes: 0

Related Questions