开发者

How do you return from two functions deep in JavaScript

The setup is like this:

var blah = function () {
    var check = false;
    verify({ success: function () {
        if... check = true;
        else... check = false;
    }});
    return check;
};

The idea is to use the verify function to check something, and then return true or false. However, the method above will always return false — returning before th开发者_开发百科e success function is called.

How do I get the results I need?


you cant,

var blah = function (callback) {
  verify({ 
    success: function () {
      if () { 
        callback(true);
      } else { 
        callback(false);
      }
     }
  });
};

blah(function(result) { 
  // my code here
});

Jquery 1.6 has a new promise api that allows you to take the return of an async call and make it look a little more synchronous, but its basically the same as this.


It looks like verify is calling the success function asynchronously?

If that is the case, what you need to do is package up what you are going to do after blah as a function - call it foo. Then within verify call into foo - for example:

    if...  { foo(true);  }
    else...{ foo(false); }


For your example, you could do something like this:

var blah = function () {
    var check;
    try{
        verify({ success: function () {
            if... throw true;
            else... throw false;
        }});
    }
    catch(e){
        check = e;
    }
    return check;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜