0

Variable ntabs in the end is empty, how i can change this code (maybe using Q, or async libs) to make it working correctly

var actions = [..];//array of objects
var ntabs = [];//arr where i put results

  actions.forEach(function(a) {
    chrome.tabs.query({url: a.url}, function(tabs) {
        tabs.forEach(function(tab) {
          var t = {
            id: tab.id,
            title: tab.title,
            url: tab.url,
            faviconUrl: tab.favIconUrl,
            actions: a.actions
          }
          ntabs.push(t);
        });
    });
  });

  console.log(ntabs);//result is empty
andymcgregor
  • 1,005
  • 2
  • 13
  • 28

1 Answers1

1

Function chrome.tabs.query is asynchronous function. You should add a counter which will execute the rest of the code when the last query is complete.

var actions = [{
  url: 'http://stackoverflow.com/questions/40696350/foreach-inside-foreach-result-is-empty-probably-because-of-async-call'
}, {
  url: 'chrome://extensions/?id=ehlnpfcjcalccnjondlokficpbkiefdk'
}];
var n = actions.length;
var ntabs = [];
actions.forEach(function(a) {
  chrome.tabs.query({
    url: a.url
  }, function(tabs) {
    tabs.forEach(function(tab) {
      var t = {
        id: tab.id,
        title: tab.title,
        url: tab.url,
        faviconUrl: tab.favIconUrl,
        actions: a.actions
      }
      ntabs.push(t);
    });
    if(--n === 0) onQuery();
  });
});

function onQuery() {
  console.log(ntabs);
}
  • it works, thank you! – andymcgregor Nov 19 '16 at 18:34
  • 1
    While `chrome.tabs.query` is asynchronous, it does not return a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) and you are not treating as if it did. – Makyen Nov 19 '16 at 18:35
  • @Makyen. Yes, correct. I forgot that only Firefox's `query` function returns a promise. –  Nov 19 '16 at 18:44
  • @SoftwareEngineer171, It does return a Promise when used as `browser.tabs.query()`, but not when used as `chrome.tabs.query()`. – Makyen Nov 19 '16 at 18:48