Question: Wrong part of code executes first

Question

Wrong part of code executes first

Answers 1
Added at 2016-12-27 19:12
Tags
Question

I need to get the current URL of the tab in order to parse it. I've written the following but then I run into a problem. The console.log in the last line is always run first, not the needed function. What causes this?

var tabURL;
chrome.tabs.query({
    active: true,
    currentWindow: true
}, function(tabs) {
    tabURL = tabs[0].url;
    console.log(tabURL);
});
console.log("Why does this run first?");

Answers
nr: #1 dodano: 2016-12-27 19:12

That's because of asynchronous execution. While JavaScript waits for the chrome API, the console goes ahead and logs your message. To fix this, you can put a callback in a callback.

var tabURL;
chrome.tabs.query({
    active: true,
   currentWindow: true
}, function(tabs) {
    tabURL = tabs[0].url;
    console.log(tabURL);
    console.log("I execute second!")
});

So as long as you put the code using the URL in the callback, it should work just fine.

Source Show
◀ Wstecz