I am confused regarding the order of evaluation in javascript. For ex, this is the code I have written
this.getTabUrl=function()
{
this.logToConsole("1"+"getTabUrl is called");
var myUrl
chrome.tabs.getSelected(null, function(tab)
{
myUrl = tab.url;
console.log("2"+tab.url);
console.log("3"+myUrl);
//this.parent.logToConsole(tabUrl);
});
this.tabUrl=myUrl;
this.logToConsole("3.1"+myUrl);
this.logToConsole("4"+this.tabUrl);
return myUrl;
}
When I call this function, this is the Output I get
> 1getTabUrl is called
> 3.1undefined
> 4undefined
> 2undefined
How come 3.1 and 4 is evaluated first before 2.
The function passed to
chrome.tabs.getSelected()is executed asynchronously.You need to put everything that needs whatever gets passed to the callback inside the callback function. Note that this means you cannot
returna value from the outer function that relies on something from the callback. You need to accept a callback argument instead and call it with the return value.