首页 > 解决方案 > 如何在承诺中检索数组值?(未捕获(承诺中)TypeError:无法读取未定义的属性“tabId”)

问题描述

我正在开发我的 chrome 扩展。我无法在承诺中检索数组值。

async function getAllTabs() {
    let allTabs = [];

    await chrome.windows.getAll({populate: true},function(windows){
        windows.forEach(function(window){
            window.tabs.forEach(function(tab){
                let url = new URL(tab.url);

                allTabs.push({windowId: window.id.toString(), tabId: tab.id.toString(), domain: url.hostname, title: tab.title, url: tab.url});

            });
        });
    });

    return allTabs;
}

let allTabs = getAllTabs();

allTabs.then(function(tabs) {
        console.log(tabs); // no prob, an array is shown
        console.log(tabs[0].tabId); // error! Uncaught (in promise) TypeError: Cannot read property 'tabId' of undefined
});

选项卡的控制台日志

但我可以获得简单字典数组的值。

let dictArray = [];
dictArray.push({tabId: 2, windowId: 3, msg: "Hello"});
dictArray.push({tabId: 8, windowId: 6, msg: "Kitty"});
console.log(dictArray); // an array is shown
console.log(dictArray[0].tabId); // 2

标签: javascriptarraysgoogle-chrome-extensionpromise

解决方案


推荐阅读