Having trouble getting a return value from a Javas

2019-08-30 07:40发布

问题:

Hey everyone - I'm having some difficulties properly getting a return value from one of my Javascript callback functions, and it looks to be dependent on a race condition, but I'm not sure:

JSOBJ.container = function() {
 return {
  getName: function() {
   var value;      
   companyfn.app.getInfo(callback);
   function callback(foo) {
    // alert("gets here");
    if (foo.hadError()) {
     alert("Error found!");
    } else {
     value = foo.getField(companyfn.app.Field.SUB_DOMAIN);
    }
    // alert('callback: ' + value);
   }
   return value;    
  }
 }
}();

JSOBJ.main = function () {
 return {
  init: function() {
   alert(JSOBJ.container.getName());
  }
 };
}();

In JSOBJ.main.init(); above, I'm trying to get the proper value, but when I run my code, I almost always get a return value of undefined. When I uncomment my alert statements in JSOBJ.container.getName(), the getName function seems to run without invoking the callback, the alert pops up, and then the getName function gets called. So it feels like a race condition, and I want to say it has to do with closures, but I'm not sure how to implement it properly so it "waits" for getField to return a value. Can anyone help?

回答1:

Pass the defined function to your ajax call (I am assuming that is an ajax call) or pass it as an anonymous lambda. Your callback function is created on the fly after the call that passes it.



回答2:

You cannot make your function block until the callback finishes without completely freezing the browser, which is not a good idea.

You need to make your getName function take a callback and give the callback its value, just like companyfn.app.getInfo.