开发者

Order of Evaluation in javascript

开发者 https://www.devze.com 2023-03-09 22:32 出处:网络
I am confused regarding the order of evaluation in javascript. For ex, this is the code I have written

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

> 1getTabU开发者_开发问答rl 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 return a 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号