Hello,

The reason it doesn't work is because the Chrome APIs are
asynchronous. The callback doesn't actually get invoked until long
after avoid_callback() returns. It's similar to the way XMLHttpRequest
works, if you're familiar with that.

There is no way to avoid this asynchronous nature. It's the downside
to the robustness Chrome gets as a result of being multiprocess.

The normal convention for dealing with async APIs in JavaScript is
something like:

var someVar = "foo";
var someOtherVar = "bar";

chrome.windows.doSomething(someVar, function(result) {
  // do stuff in here with someVar, someOtherVar, and result
});

You can nest this pattern deeply to deal with multiple async APIs. You
can read up on how this works by doing a google search for:
[JavaScript closures].

Good luck! And if you have a more detailed use case, someone can
probably help with sample code that shows the common JavaScript way to
do it.

- a

On Sun, Jun 7, 2009 at 11:10 AM, disya2<[email protected]> wrote:
>
> Hi,
>
> I'm developing an extension. What I'm trying to do is to avoid
> callback-style calls for chrome.tabs, etc.
>
> Here is the code I wrote to accomplish that
>
> function avoid_callback(what, func, args) {
>    var x, callback = function (y) {x = y;};
>    if (!args || !args.length)
>        args = new Array();
>    args.push(callback);
>    what[func].apply(what, args);
>
>    return x;
> }
>
> Then the call would be
> var tabs = avoid_callback(chrome.tabs, "getAllInWindow", windowId);
>
> For some reason I get tabs _undefined_.
>
> The avoid_callback function was tested in Firefox, the exact code used
> is
>
> var obj = {  f: function(x, c) { c(x); } };
> alert(avoid_callback(obj, "f", [1]));  // this shows 1
>
> I can't figure out why it doesn't work for chrome.tabs.
>
> Another question: maybe there is a way for elegant callback use which
> I'm not aware of? In general, I'm trying to avoid the code like
>   // find id of the current window
>    var win_id = null;
>    chrome.windows.getCurrent(function (win) {
>            win_id = win.id;
>        });
>    this.win_id = win_id;
>
>
> Thanks,
> Denis
>
> PS. Google Chrome 3.0.182.3 32 bit for Windows running on Ubuntu 8.04
> with Wine 1.1.22
>
> >
>

--~--~---------~--~----~------------~-------~--~----~
Chromium Discussion mailing list: [email protected] 
View archives, change email options, or unsubscribe: 
    http://groups.google.com/group/chromium-discuss
-~----------~----~----~----~------~----~------~--~---

Reply via email to