Over the period of three months, I have been a mentee at the She Code Africa Bootcamp and wrapping up my learning process, I'm writing about a technique I learned.
If you don’t understand Async JS, don’t worry, stay with me. This article aims to get you to understand it as much as possible. Hence “Like I'm Five”
Before reading through this, you’re expected to have a basic understanding of JavaScript and its syntax.
First off, what does Asynchronous mean? Simply put, it is non-simultaneous. It is a series of stuff that doesn’t have to happen at the same time. For example, asynchronous communication happens when information can be exchanged independent of time. Like your Emails, you get an email, and if it's not urgent, you can reply at your convenience. I hope you understand this?
So, plain JavaScript i.e., Vanilla JS is normally a Synchronous language aka Single-threaded. This means it executes codes in order. i.e., If there is a list of codes in your editor, it must finish executing the first one, before moving to the second or third.
And so, if a function relies on the result of another function to progress, it’d have to wait for the other function to finish and return the result. Until that happens, the program is stopped for the time being. Waiting on results can get very frustrating instead of progressing and this eventually leads to the basis of Asynchronous Programming.
In this type of programming, the web browser provides you with an API (Application Programming Interface) that you'd fetch to help run your tasks asynchronously. The APIs are fetched from an external device or a server. i.e., accessing a database and returning data from it. There are two main types of asynchronous code styles. The old style known as Call-backs and the new style known as Promises.
Let’s start with Async Call-backs
They are functions specified as arguments. When calling a function that’d execute code in the background, and the code finishes running, it calls back the function to let you know that the work has been completed. An example is the addEventListener () method
btn.addEventListener('click', () => {
alert('You clicked me!');
let pElem = document.createElement('p');
pElem.textContent = 'This is a newly-added paragraph.';
document.body.appendChild(pElem);
});
The first parameter is the type of event to be listened for, and the second parameter is a call-back function that is invoked when the event is fired. When a call-back is passed as an argument to another function, it is not executed immediately. It is “Called back” Call-backs are very versatile. They allow you to control the order in which the functions are run and also allow you to pass data to different functions.
Next, we have Promises
This is a new style of async used in web APIs an example is the fetch() API,
which is the modern version of XMLHttpRequest. Below is an example:
fetch('products.json').then(function(response) {
return response.json();
}).then(function(json) {
let products = json;
initialize(products);
}).catch(function(err) {
console.log('Fetch problem: ' + err.message);
});
Here we see fetch() taking a single parameter — the URL of a resource you want to fetch from the network i.e (products.json) — and returning a promise.
A promise is an object representing either the completion or failure of the operation. It’s a simplified manner of the browser saying “I promise to get back to you with the answer as soon as I can.” Promises need practice getting used to.
Neither of the possible outcomes has happened yet, so the fetch operation is currently waiting on the result of the browser trying to complete the operation at some point in the future. We've then got three further code blocks chained onto the end of the fetch():
Two .then()
blocks both contain a callback function that will run if the previous operation is successful, and each callback receives as input the result of the previous successful operation, so you can go forward and do something else to it.
Each .then()
block returns another promise, meaning that you can chain multiple .then() blocks onto each other, so multiple asynchronous operations can be made to run in order, one after another.
The .catch()
block at the end runs if any of the .then() blocks fail.
The Event Queue
Call-backs and Promises are put in an event queue, which runs after the main thread so they don’t block other codes from running. The queued operations will complete as soon as their results are returned to the JS environment.
Promises Versus Call-backs
Promises have some similarities to call-backs but promises were specifically made for handling async operations and have many advantages over call-backs . Multiple async operations can be chained using multiple .then() operations, passing the result of one into the next as input. This is much harder to do with call-backs as it leads to call back hell.
. Promise call-backs are always called in the strict order they are placed in the event queue
. Error handling is much better since we’d be using the .catch()
block at the end of the block
I hope you have been able to understand it to an extent? If no, there’s no problem. It really takes some getting used to. There’s no crime in going over it as many times for it to stick. You could also check other materials and video resources for better understanding.
Thank you for reading!