简体   繁体   English

JavaScript 不等待循环

[英]JavaScript doesn't wait for loop

I'm making a Google Chrome extension.我正在制作 Google Chrome 扩展程序。 I'm trying to open new tabs and group them.我正在尝试打开新标签并将它们分组。 I have urls as an array.我有 urls 作为一个数组。 But chrome.tabs.group function doesn't wait until all tabs open.但是 chrome.tabs.group function 不会等到所有选项卡都打开。

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.当 ourTabIds 仍然为空时,组 function 工作。 So it gives errors.所以它给出了错误。

Why it doesn't wait?为什么不等? How can I fix that?我该如何解决?

You could promisify chrome.tabs and then use Promise.all您可以承诺chrome.tabs然后使用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. function chrome.tabs.create()使用回调作为参数。 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 )您应该将其转换为 Promises 并使用.then() 完成所有操作,或者检查它是否是最后一个 url (从of更改为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)}) 
             }
        })
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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