Asynchronous JavaScript: The Complete Guide - Part 2 - Callbacks

Ronaldo B.August 1, 20229 min read

In this article, we will talk about callback functions and how they helped in the development of Asynchronous JavaScript. You can check the content of part 1 of this series at this link:

Asynchronous JavaScript: The Complete Guide - Part 1 - What is an asynchronous code?

What are callbacks

A callback function is basically a function executed after another. For this function to be executed, we usually inform it as a parameter of an initial function. To better understand this concept, think of the following example: when you were a child, did you ever receive some tasks from your mother? Perhaps you remember receiving a list of tasks. Example: “wash the dishes, sweep the room, and tidy your bedroom.” You did all of that. But, at the end of the day, she tells you: “I forgot one more thing: take out the trash.” Did you notice? You completed several tasks, but in the end, she handed you one more to do. A callback function works the same way. We execute a function that will perform several actions. But we also inform a function in the parameter, as if saying: “after executing everything I’ve already defined, perform this additional task in the parameters.”

But why should we use a callback function? In some cases, we just want to execute an action after something has already occurred on the page. Example: imagine that we want to render a list of cities in a table. However, the information about the cities is coming from an API. So, when will we perform the rendering? Only when we actually have the data, right? In this case, we could create a rendering function that would be the callback of the main function, which would be responsible for bringing the data.

Two classic examples of callback functions are the setTimeout() and setInterval() functions, which are native to JavaScript. Both expect a return function. But what do you think about creating a callback function together? Check out the code below:

function writeHello(callback) {
	console.log('Hello World');
	if (typeof callback == 'function') callback();
}

We created a function called writeHello() that will display “Hello World” in the console. But, in addition to that, we expect a variable called callback as a parameter. And notice that in the last line of the function we check what type the variable is, to ensure it is a function and then we call this variable with parentheses at the end of its name, making it clear that it is a callback function.

Now see how we could execute the writeHello() function:

writeHello(function() {
	console.log('Callback Function');
});

Very interesting, don’t you think? We called the writeHello() function and already provided an anonymous function, a callback function, which will also display a message in the console.

If we access the console while executing this code, we will see the following result:

Both messages were displayed, as both functions were executed.

This is the concept of callback functions. But, as we talked about in the previous article, we will create a website that will consume an API and display the information on the screen. What do you think about starting to develop this project, putting into practice what we learned about callbacks? Ready? Then, let’s go!

All the codes we develop will be available on our GitHub.

First, let’s explain the structure of the project:

Project Structure of Visual Studio Code

We have a folder for style files, a folder for JS files, a folder for image files, and finally our HTML file, which serves as the entry point for the project.

Regarding external tools, we will only use Materialize.css to make our page a little more pleasant and easier to style.

Initially, our project looks like this:

Our Hcode Games Project

Now, let’s get into the logic of the project. Our goal is to type the name of a game in the search box and have the results rendered in the main games area. First, we will need a function to consume the game API. We will create these functions inside a file called requests.js, which will be located inside the js folder.

The first function will be called getGameByName() and will expect two parameters: the name of the game we are looking for and a callback function, which is the theme of this article. Its code will look like this:

function getGameByName(name, callback) {
    let request = new XMLHttpRequest();
    request.open('GET', `https://api.rawg.io/api/games?search=${name}`, true);
    request.onload = () => {
        let response = JSON.parse(request.response);
        if (typeof callback == 'function') callback(response);
    };
    request.send();
}

Explaining the function: we will create an XML request using the XMLHttpRequest() class. Remember that we taught the various features of this class and how to manipulate it in our Complete JavaScript Course.

Continuing the explanation. After creating this XML request, we will access the API URL, providing the name we expect there in the function arguments. When we obtain the data, we will convert it to JSON and, now note, execute the callback function, providing the game data to this function. Thus, we can do whatever we want with this information, that is, we can render them on the screen. Now we need to call this function we just created. The name of this function will be initGames().

Before that, going back to the HTML file, let’s open a