Samrat
Samrat

Reputation: 367

How to solve asynchronous in using Javascript?

How can i modify the following code to run in a synchronous way ? The AddonManager is an asynchronous call and I could not able to get the proper result.

function initWithPrivs (java, ext_id, jarFiles) {

    var [loader, urls] = init(java, ext_id, jarFiles);
    policyAdd(loader, urls);
    return [loader, urls];
}

function init (java, ext_id, jarFiles) {

var classLoader;
var fURLs=[];
    JAVA = java;
    try {  

      Components.utils.import("resource://gre/modules/AddonManager.jsm");  
 AddonManager.getAddonByID("[email protected]",function(addon) {  

     //Some code to process fURLs and classLoader
     //If i put return here its shows me error 
}
);
  return [classLoader,fURLs];  //If i use return here it return null.
}
catch(Exception e)
{
}

Upvotes: 2

Views: 512

Answers (2)

Jim
Jim

Reputation: 61

Would it not be better to do:

  var addonObj = -1;
AddonManager.getAddonByID("[email protected]",function(addon) {
    addonObj = addon;
});
var thread = Components.classes["@mozilla.org/thread-manager;1"].getService().currentThread;
while (addonObj != null || addonObj == -1)
  thread.processNextEvent(true);
// addonObj is no longer null...

in case the Addon is not installed?

Upvotes: 0

erikvold
erikvold

Reputation: 16558

You shouldn't make this code sync, use the async method.

So, I do not recommend doing this, but I'll mention it anyhow, you could do something like:

var addonObj = null;
AddonManager.getAddonByID("[email protected]",function(addon) {
    addonObj = addon;
});
var thread = Cc["@mozilla.org/thread-manager;1"].getService().currentThread;
while (addonObj == null)
  thread.processNextEvent(true);
// addonObj is no longer null...

Upvotes: 1

Related Questions