Basically, Asynchronous style code means start executing now and finish it later. In the above scenario, when getting data from API or Database. We use Asynchronous functions instead of Synchronous functions. Then that function can start now and finish later once the data received. when executing code if there is Asynchronous code it will be removed from the call stack and the browser is going to tracks until finishes the task. then other statements can execute without any delay. Now I will explain it using the set timeout function which is asynchronous.
Here, we will discuss callbacks, promises, and async-await syntax. Basically, these are the ways to deal with asynchronous data.
Multiple functions can be created independently and used as callbacks and these will create a multi-level function and when you have too many of these nested functions code becomes impossible to read. This drawback is called callback hell and let’s take a look at an example for better understanding.
Callback functions are useful for short asynchronous tasks. Due to this, promises were introduced to overcome this issue in ES6.
Promises, the name explains itself exactly. It is a promise to do something if something else is true and if it is not true then it won’t. Promises used to handle the asynchronous results of a task and a lot cleaner syntax than callbacks. In this scenario, isTrue is acting as a result based on the result resolve function or reject function will be called. Then, then method will be called on the promise if the resolve is called and the catch method will be called if the reject method is called. Anything inside then will be run for resolve and anything inside catch will be run for reject. Normally catch is used to handle errors.
Async/Await is really just syntactical sugar wrapped around making promises easier to work with. It is a way to write asynchronous code like synchronous code. When using the async keyword before the function that function will return a promise. This means, this takes a return value and automatically resolves it as a promise. Also, sets up a context to use the await keyword this will be work only inside the async functions. Here, we use try and catch for error handling.