Asynchronous JavaScript and Callbacks — a Simple Summary

Asynchronous codes are basically codes that do not complete their execution according to the regular flow of the code blocks in a script. In other words, the code blocks that come after an asynchronous code may complete their execution before the asynchronous code.

So, What Is the Big Deal With Asynchronous Codes?

The following is an example of a regular script (one without asynchronous codes):

console.log(“script start”); // prints to the console firstlet data = [];function sum(a, b) {c = a + b;data.push(c);console.log(data);}sum(1, 2); // prints to the console secondconsole.log(“script done”); // prints to the console in third place

As you can see, the codes in the script above are executed according to the way they are called. But if we have an asynchronous code, like the XMLHttpRequest() below, the code blocks in the script will not be executed in the order they are called.

See below:

console.log(“script start”); // first execution: this prints to the consolefunction fetchData(url) {const xmlhr = new XMLHttpRequest();xmlhr.open(“GET”, url);xmlhr.send();xmlhr.onload = function () {if (xmlhr.status === 200) {console.log(xmlhr.responseText);} else {console.log(xmlhr.status);}};return xmlhr.onload;}const url = prompt(“Enter URL”); // second execution: this prompts an inputfetchData(url); // fourth execution: this returns the result of xhr.onloadconsole.log(“script done”); // third execution: this prints to the console

As said before, asynchronous codes do not follow the regular flow of the program or script. So, any code that needs a value from the asynchronous code for its own execution will not work as it should.

If a code needs a value from the asynchronous code in your script, the code could either:

· Wait for the complete execution of the asynchronous code before it completes its own execution.

· Throw an error.

To avoid a situation where a code throws an error because it depends on an asynchronous code, callbacks are added to asynchronous codes.

Callbacks

Callbacks are functions used as arguments in another function. They offer some control over the sequence in which the codes in a script are executed.

By adding a code as a callback to an asynchronous function(asynchronous code), you ensure that such code will only execute when the asynchronous function completes its execution. This way, the code will only be initiated when it gets a value from the asynchronous function. Hence, it will not throw an error.

If we include callbacks to the asynchronous script above, we will get the following:

console.log(“script start”); // first execution: this prints to the consolefunction fetchData(url, success, errorMessage) {const xmlhr = new XMLHttpRequest();xmlhr.open(“GET”, url);xmlhr.send();xmlhr.onload = function () {if (xmlhr.status === 200) {success(xmlhr.responseText);} else {errorMessage(xmlhr.status);}};}//success and errorMessage are callbacks. Either of them will execute, depending on the result of the fetchData() function called after them. They will not throw an error because they will surely wait for the asynchronous function — fetchData().function success(output) {console.log(output);}function errorMessage(status) {console.log(`Error ${status}!`);}const url = prompt(“Enter URL”); // second excution: this prompts an inputfetchData(url, success, errorMessage);console.log(“script done”); // third execution: this prints to the console

By making them callbacks, the two functions that need a value from the asynchronous function will not throw an error. Being callbacks in the asynchronous function, they are compelled to wait for the asynchronous function before they execute.

Summary

Normally, JavaScript codes execute in the order in which you call them. However, an asynchronous code will not follow this regular flow. This means an asynchronous code will most likely execute later than a code you called after it.

If the execution of a code called after an asynchronous code is dependent on the value returned by the asynchronous code, it may throw an error. To avoid this, such codes are added to the asynchronous functions (asynchronous codes) as callbacks.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store