title: Javascript synchronous flow when there are asynchronous function call
body: <p>I spent all day reading about jquery deferred, promise, etc.</p>
  
  <p>My problem is really simple. </p>
  
  <p>I have one function that call 4 other functions, and some of them have async calls to fetch data from the server.</p>
  
  <pre><code>function A() {
      async call
      console.log("1");
  }
  
  function B() {
      normal code
      console.log("2");
  }
  
  function C() {
      async call
      console.log("3");
  }
  
  function xyz() {
      A();
      B();
      C();
      print str;
  }
  </code></pre>
  
  <p>the expected result is 123str.</p>
  
  <p>instead i get 312 or 213. Basically the 3 functions don't wait the end of the other one. I have tried with .done with $.when(a).then(b), with promise.</p>
  
  <p>But nothing work. Can someone give me a barebone example code that works?</p>
  
  <p>EDIT: </p>
  
  <pre><code>function setId() {
  
  var doc = sessionStorage.getItem("urlDoc");
  var user = sessionStorage.getItem("LoggedUser");
  var string = "urlDoc=" + doc + "&amp;user=" + user;
  if (sessionStorage.getItem("countId") === null) {
      $.ajax({
          type: 'POST',
          url: 'php/findTemporaryId.php',
          data: string,
          success: function (data) {
              sessionStorage.setItem("countId", data);
              countId = sessionStorage.getItem("countId");
              id = countId;
              console.log("1");
  
          },
          error: function () {
              alert("Server Error");
          }
      });
  } else {
      sessionStorage.setItem("countId", parseInt(sessionStorage.getItem("countId")) + 1);
      countId = sessionStorage.getItem("countId");
      id = countId;
      console.log("1");
  
  }
  </code></pre>
  
  <p>then</p>
  
  <pre><code> function setAuthor() {
      author = sessionStorage.getItem('LoggedUser');
      console.log("2");
  
   }
  </code></pre>
  
  <p>then</p>
  
  <pre><code>function getData() {
      $.ajax({
      type: 'POST',
      url: 'php/date.php',
      success: function (data) {
          date = data; 
          console.log("3"); 
      },
      error: function () {
          alert("Error");
      }
  });
  }
  </code></pre>
  
  <p>this is how i call them</p>
  
  <pre><code>function saveSelectionFragment() {
  
          setId();
          setAuthor(); 
          getData();
  }
  </code></pre>
  
  <p>here the firebug console.
  <a href="https://i.imgur.com/zQ0Mk4E.jpg" rel="nofollow noreferrer">http://i.imgur.com/zQ0Mk4E.jpg</a></p>