Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you return from two functions deep in JavaScript

Tags:

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 the success function is called.

How do I get the results I need?

like image 425
arjs Avatar asked May 05 '11 21:05

arjs


2 Answers

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.

like image 142
Dale Harvey Avatar answered Oct 18 '22 06:10

Dale Harvey


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); }
like image 28
Justin Ethier Avatar answered Oct 18 '22 07:10

Justin Ethier