Q:

Return result of XMLHttpRequest

I'm trying to return the result of an XMLHTTPRequest:
<a href="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">Click me for Google CDN jQuery!</a> 

<script>
    const url = {
        httpRequest: function(callback) {
            var xhr = new XMLHttpRequest();
            xhr.addEventListener("load", callback);
            xhr.open("GET", document.querySelector("a").href); // Using querySelector to simulate how my real program works - I don't want to hardcode anything mainly because this should be dynamic.
            xhr.send("");
        },
        compileData: function(data) {
            var response = data.target.responseText.substring(4, 17) 
            // I can't figure out how to take this response and 'return' it.
        },
        getContent: function() {
            url.httpRequest(url.compileData)
        }
    }

     var content = url.getContent() // I want 'content' to be equal to "jQuery v3.3.1"
</script>

But, I can't figure out how to 'return' the response.
Yes, I know that there are other questions out there like this one, namely: How do I return the response from an asynchronous call? But, I'm new to JavaScript and have no idea how to integrate what they're saying there into my case.

A:

You need Promises, Promises and more Promises! And you should return one from your function.
function httpRequest() {
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();
        xhr.onload = (response) => {
            resolve(response); // You should check the response and maybe preprocess it 
                               //   so that not everything is passed further
        }
        xhr.open("GET", document.querySelector("a").href);
        xhr.send("");
    });
}

and then you may use then and catch
httpRequest().then((data) => {
    // Yay! Got response from the server!
}).catch((error) => {
    // Yay! More errors!
});

