-1

I'm writing a Chrome Extension. I have the following piece of code.

function getCurrentTab() {
  var r;
  chrome.tabs.query({
    active:true,
    currentWindow:true
  },function (tabs) {
    r=tabs[0];
    console.log(r);
  });
  return r;
}

console.log(getCurrentTab());

I expect this function to return the active tab. Unfortunately the attribution inside the callback function doesn't affect r from the parent function getCurrentTab and I can't figure out why is that.

At the moment this code writes to console:

undefined
Object {active: true, height: 954, highlighted: true, id: 16, incognito: false…}

Desired result would be:

Object {active: true, height: 954, highlighted: true, id: 16, incognito: false…}
Object {active: true, height: 954, highlighted: true, id: 16, incognito: false…}
pandronic
  • 631
  • 2
  • 9
  • 21
  • The callback you are passing to the query function is asynchronous, so the assigment isn't happening until after getCurrentTab has returned. – Jack Dec 22 '13 at 16:42
  • Pass a callback function to the getCurrentTab method that is called in the query callback, and takes 'r' as an argument. – Jack Dec 22 '13 at 17:53
  • @rsanchez - I don't want to move my logic in the callback function, like the solution suggested in the linked question. – pandronic Dec 22 '13 at 18:29
  • @Jack Newcombe - Sorry, I don't understand. Would you mind giving an example? Thanks – pandronic Dec 22 '13 at 18:42
  • Sure I'll post it as an answer. – Jack Dec 22 '13 at 18:45
  • There isn't a way to do this without using a callback function unless a synchronous version of query is provided (which is unlikely). – Jack Dec 22 '13 at 18:50

1 Answers1

0

As the callback for the query function is asynchronous, you need to provide a callback function to the getCurrentTab function and do your operations in there:

function getCurrentTab(callback) {
    chrome.tabs.query({
        active:true,
        currentWindow:true
    }, function (tabs) {
        callback(tabs[0]);
    });
}

getCurrentTab(function(r){
    console.log(r);
    // ... other operations using current tab ...
});
Jack
  • 662
  • 5
  • 14
  • Unfortunately, this doesn't solve my problem. I'd prefer it if it were possible to avoid using any callbacks. Thanks. – pandronic Dec 22 '13 at 18:54
  • Evidence suggests that you can't avoid it: http://stackoverflow.com/questions/17748101/chrome-extensions-make-chrome-tabs-query-synchronous – Jack Dec 22 '13 at 19:40
  • Seems that way and it sucks :( – pandronic Dec 22 '13 at 20:19
  • If you're worried about control flow, you could consider using promises: https://github.com/bellbind/using-promise-q/ – Jack Dec 22 '13 at 20:45