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 !
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 :
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 .
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
.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 storing the data in a database or for sending the data to an API or web server.