(I think that this is a callback issue, but I’m not completely sure)
I have a function that wants to retrieve data from all tabs. It looks like:
function retrieveData(callback) {
getAllTabs(function(openedTabs) {
for(var t=0; t<openedTabs.length; t++) {
//get data from this tab
}
});
//log(look at updated data)
}
function getAllTabs(callback) {
if(callback) {
chrome.windows.getAll({populate: true}, function(windows) {
//get tabs from windows; callback(tabs)
});
}
}
My problem is not that I don’t get the data from the tabs. That works fine. It’s that if I call retrieveData, the functions occur in an order s.t. I don’t get the data until after I’ve already left function retrieveData, i.e. if I look at my data right where that log statement is in getAllTabs, there are no updates.
How do I fix this so that the data is there in a sequential order?
I’m not sure I quite understand the phrasing of the problem, but I think the problem is that you’re dealing with asynchronous requests not synchronous requests. When you call
chrome.windows.getAll, the function does not return all the tabs right away. Instead, you’re saying to Google Chrome: “I want all the tabs, but don’t give it too me right away. When you have all the tabs, run this callback function”.If you want to run
log(look at updated data)sequentially after getting all the tabs, you should put it inside the callback function you pass togetAllTabs