teMkaa teMkaa - 19 days ago 5
Javascript Question

Foreach inside foreach, result is empty probably because of async call

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

Answer

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);
}