Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在promise中检索数组值?(未捕获(承诺中)TypeError:无法读取未定义的属性';tabId';)_Javascript_Arrays_Google Chrome Extension_Promise - Fatal编程技术网

Javascript 如何在promise中检索数组值?(未捕获(承诺中)TypeError:无法读取未定义的属性';tabId';)

Javascript 如何在promise中检索数组值?(未捕获(承诺中)TypeError:无法读取未定义的属性';tabId';),javascript,arrays,google-chrome-extension,promise,Javascript,Arrays,Google Chrome Extension,Promise,我正在开发我的chrome扩展。我无法在promise中检索数组值 async function getAllTabs() { let allTabs = []; await chrome.windows.getAll({populate: true},function(windows){ windows.forEach(function(window){ window.tabs.forEach(function(tab){

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

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

chrome.windows.getAll
是否返回承诺?没有多少返回承诺的函数也接受回调-因此,
等待
调用不返回承诺的函数根本不会等待异步进程,因此返回的是空数组。它回报了一个承诺。在“then”之后,会显示一个数组。我打赌它不会。。。问题是,控制台可能会骗你。。。
没有问题,显示了一个数组这一事实并不意味着数组就在代码中的那个点上。。。如果你不相信我,试试这个<代码>控制台.log(tabs.length)
-我打赌它显示零。。。嗯,也许不是,但是试试看。你是对的。它是零。那么我该怎么做才能得到数组值呢?首先,你需要意识到
chrome.windows.getAll
不会返回一个承诺。。。将代码更改为
let x=chrome.windows.getAll。。。。。etc
then
console.log(x)
-如果这不记录承诺对象,那么您需要重新考虑如何“等待”异步操作结束