So while drowning in Preact.js and Reef research for a project, I saw a fetch() method somewhere. One new tab led to another, and I found out just how far behind my JavaScript was.

In the process, I also learned things like const and var and let go of my fear of Promises and Terry Venables thenables by avoiding them completely with Async-Await.

What I wanted to do was to move away from XMLHttpRequest towards Fetch to reduce render blocking. So this is how I used to do load in my JSON bits before:

function loadContentFromExternalFile() {
    var requestURL = "/my/data/file.json";
    var request = new XMLHttpRequest();
    request.open("GET", requestURL, true);
    request.responseType = "json";
    request.send();

    request.onload = function() {
        var retrievedData = request.response;
        if (typeof retrievedData === "string") {
            retrievedData = JSON.parse(retrievedData);
        }
        doSomeThingsWithMy(retrievedData);
    }
}

After porting to the Fetch API, the same function looks like so:

async function loadContentFromExternalFile() {
    let requestURL = '/my/data/file.json';
    let reqResponse = await fetch(requestURL);
    var retrievedData = await reqResponse.json();
    doSomeThingsWithMy(retrievedData);
}

It’s asynchronous, easier to read, there’s lesser code, and no need to use a stupid function name where XML is in all caps but HTTP is ‘Http’. Does it perform better? Time to learn how to make the most of console.time().