title: How to make a function which returns the response of an ajax request
body: <p>I have a function which makes an ajax request (see code below), how do I return the response?</p>
  
  <p>Code:</p>
  
  <pre><code>const ajaxreq = (url) =&gt; {
      let xhttp = new XMLHttpRequest();
      let res = "";
      xhttp.onreadystatechange = _ =&gt; {
        if (this.readyState === 4) {
          res = this.responseText
        }
      };
      xhttp.open("GET", url, true);
      xhttp.send();
  }
  </code></pre>
  
  <p>I have tried placing the return statment inside the <code>xhttp.onreadystatechange</code>, but this doesn't make the function <code>ajaxreq</code> return that value, only the anonymous function. If I place the return statement after <code>xhttp.send();</code>, then the request doesn't have enough time to fulfill and the function just returns an empty string.</p>
  
  <p>How can I solve this problem?</p>