title: Javascript function returns before its subroutine finishes
body: <p>I'm trying to test if urls dynamically passed to image tags would resolve or not. I'm using the following javascript function: </p>
  
  <pre><code>    testImageUri = function(src) {
          var img = new Image();
          var imgStatus = false;
  
          var goodUri = function() {
              imgStatus = true;
          };
  
          var badUri = function() {
              imgStatus = false;
          };
  
          img.onload = goodUri;
          img.onerror = badUri;
          img.src = src;
  
          return imgStatus;
      }
  </code></pre>
  
  <p>The functions badUri and goodUri get called as expected, but they appear to be "late" as the testImageUri function seems to return before they get to change the imgStatus variable.</p>
  
  <p>How do one resolve such problems in javascript?<br/>
  How do one avoid them?<br/>
  is there a rule of thumb to recognize situations susceptible to create this?</p>
  
  <p><strong>EDIT</strong>
  <br/>Thanks all for your replies. I think I understand what's going on now. I will be implementing the function as described in the first reply, but with an additional parameter for the callback as suggested.</p>
  
  <p>Thanks again.</p>