Search code examples
javascriptarraysgoogle-chrome-extensionforeach

Unable to print each element in javascript array despite being able to print whole array


I have the 2 functions below. The first pushes tabs to currentTabs. The second is supposed to iterate over them, but it is showing a length of 0. However I am able to print the whole array to the console.

let currentTabs = [];

async function getCurrentTabs() 
{
  chrome.tabs.query({}).then((tabs) =>
  {
    for ( const tab of tabs) 
    {
      currentTabs.push(tab);
    }
  });
}
...
async function showTabsToSave()
{
  console.log("creating list of potential tabs to save");
  await getCurrentTabs();
  console.log(currentTabs); // this works
  console.log(currentTabs.at(0)); // this is undefined

  currentTabs.forEach((i) =>{
    console.log(i); // shows nothing since size is 0
  })

output


Solution

  • To solve the immediate problem, wait for chrome.tabs.query to finish with await:

    await chrome.tabs.query({}).then(/*...*/);
    

    However, it is better to actually return the array from the getCurrentTabs function than to add to a global array.

    async function getCurrentTabs() {
      return chrome.tabs.query({});
    }
    async function showTabsToSave() {
        const currentTabs = await getCurrentTabs();
        // ...
    }