title: How to write custom async function in Node.js
body: <p>I am new to javascript, trying to understand async function invocation.
  Here is my js program:</p>
  
  <pre><code>var notify =  function () {
      console.log('before');
      doPost('data', (res) =&gt; {
          console.log('callback received');
      });
      console.log('after');
  }
  var doPost = function (data) {
      console.log(data);
      while (true) {
          //do nothing
      }    
  }
  notify();
  </code></pre>
  
  <p>If my understanding is correct, notify()-->doPost() is async manner, therefore 'after' should be printed immediately after 'before'. But that does not happen. My program wait infinite loop to complete first.
  I know there is some loophole in my understanding. Please help.</p>
  
  <p>I tried these below two programs:
  This one again shows sync behavior. Prints:-
  before
  data  </p>
  
  <pre><code> var notify = function () {
      console.log('before');
      doPost('data').then((res) =&gt; {
          console.log('callback received');
      });
      console.log('after');
  
  }
  var doPost = function (data) {
      console.log(data);
      return new Promise((resolve, reject) =&gt; {
          resolve('resolved');
          while (true) {
              //do nothing           
          }
      });
  };
  notify();
  </code></pre>
  
  <p>However if I just remove the infinitely running while loop, it start showing async behaviour. Prints:-
  before
  data
  after
  callback received</p>
  
  <pre><code>var notify = function () {
      console.log('before');
      doPost('data').then((res) =&gt; {
          console.log('callback received');
      });
      console.log('after');
  
  }
  var doPost = function (data) {
      console.log(data);
      return new Promise((resolve, reject) =&gt; {
          resolve('resolved');
          while (false) {
              //do nothing           
          }
  
      });
  };
  notify();
  </code></pre>
  
  <p>This is beyond my understanding. Any help would be highly appreciated.</p>