EP-7 : Asynchronous JavaScript Programming and Basics of API
callbacks, Promises , async/await , HTTP requests
Welcome to the episode 7 of “About SWE Weekly” : A Weekly newsletter designed to stay up-to-date on the latest trend in software engineering, covering tech stacks and case studies from SWE world !
Today, we will be looking at one of the important concept in Javascript .
Javascript is a synchronous, blocking, and single threaded language. That means the code runs in sequence, and we cannot move onto the next code line before the previous one is completed. Imagine, if some intermediate task took longer than expected and nothing else worked until that task was complete. No one wants a slow, unresponsive website. To overcome this, the browser gives us a Web API that the JavaScript engine itself doesn’t provide. This includes the DOM API, setTimeout, HTTP requests, and so on. This can help us create some async, non-blocking behavior. Functions running in parallel with other functions are called asynchronous. With asynchronous programming, JavaScript programs can start long-running tasks, and continue running other tasks in parallel.
Firstly,
setTimeout( callback_fun() , 2000 ) - This function lets us delay the callback function for a specified duration of time or more without blocking the main thread.
( i.e., Behind the scenes, the callback function is added into the web API for exactly the specified duration, then kept in the callback queue until the call stack is empty, and finally moved into the call stack where it is executed. More here → visualisation )
For example, Here I created a login function, and passed 3 values, namely username , password, and a callback function that returns userID. Notice, how we managed to unblock our code flow.
Next, we want to retrieve tweets for the userID and also comments for those tweets. If you implement it in the following way ( callback inside a callback inside a callback ), that would lead to callback hell, leading to unmanageable code.
So, we have two solutions to avoid callback hells :
Promises : JavaScript Promises are easy to manage when dealing with multiple asynchronous operations.
The promise constructor takes only one argument, which is a callback function
This callback function takes two arguments, resolve and reject
Perform operations inside the callback function and if everything goes well, call resolve.
If desired operations do not go well then call reject.
.then() method is defined as a carrier that takes data from a promise and further executes it successfully.
Now what if, the API related to a particular promise returns you an error?For instance, if you couldn’t login successfully; then, the reject method is called and any parameter you passed into the reject method can be accepted using .catch()
async and await - async and await make promises easier to write
async keyword makes a function return data from Promise . await keyword makes a function wait for the completion of the previous promise. The below example should make it clear to you.
So, you see how simple the code looks now? All we did was, instead of using callback functions, implement asynchronous programming through promises, async and await .
API handling in Javascript
Next of, If you are new to API, it stands for Application Programming Interface, and is used for interacting with software applications and servers.
We’ll be using a free dummy API provided by JSON Placeholder to clearly illustrate some examples. It has 6 different endpoints , and we'll request from the /posts
endpoint.
.fetch() is a promise-based interface for fetching resources by making HTTP requests to servers. So, let’s define an async function to fetch posts.
Similarly, we can define methods for all other HTTP requests. Below, I implemented a method to add new posts to the server . Note that we always serialize the JSON data to strings for sending the data to an API or web server.