Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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();
    // ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading