title: How to make code wait while calling asynchronous calls like Ajax
body: <p>I am looking for something like this</p>
  
  <pre><code>function someFunc() {
  
  callAjaxfunc(); //may have multiple ajax calls in this function
  someWait(); // some code which waits until async calls complete
  console.log('Pass2');
  
  }
  
  function callAjaxfunc() {
    //All ajax calls called here
    console.log('Pass1');
  
  }
  </code></pre>
  
  <p><strong>What I have tried?</strong></p>
  
  <p><strong>1</strong>
      Jquery.when()</p>
  
  <p>tried using it..it works fine. But not the way I want. <code>$.when</code> will wait but the code next to <code>$.when()</code> runs with out waiting. The code inside <code>do callback</code> only runs after ajax calls</p>
  
  <p><strong>2.</strong>
  setTimeOut() with a global flag</p>
  
  <p>I was so confident this will work. I tried like following.</p>
  
  <pre><code>GlobalFlag = false;
  
  function someFunc()     
      callAjaxfunc(); //may have multiple ajax calls in this function
      setTimeOut(waitFunc, 100); // some  which waits until async calls complete
      console.log('Pass2');
  }
  
  function callAjaxfunc() {
      //All ajax calls called here
      onAjaxSuccess: function() {
          GlobalFlag = true;
      };
      console.log('Pass1');    
  }
  
  function waitFunc() {
      if (!GlobalFlag) {
          setTimeOut(waitFunc, 100);
      }
  }​
  </code></pre>
  
  <p>Still not able to get wanted result. Am I doing something wrong here? This is not the way?</p>
  
  <p>Result I wanted should come like this</p>
  
  <pre><code>Pass1
  Pass2
  </code></pre>
  
  <p>Not able to make any fiddle as it needs AJAX calls</p>
  
  <p><strong>EDIT</strong>: As many were suggesting callbacks..i know about them..but still the code next to <code>somewait()</code> will get executed...I want browser to completely stop executing code next to <code>somewait()</code> until the ajax call..Also it may be a bad practice but worth to know and try if possible...</p>