Search code examples
javascriptasynchronousgoogle-chrome-extension

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?


Solution

  • 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)})
    
    })()