简体   繁体   中英

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM