For solving the above problem asynchronous came into the picture. Asynchronous programming makes it possible to express waiting for long-running action without freezing the program during these actions.
The callback is a function that is passed inside another function as an argument for executing later. This method is very efficient, but only to a certain point, sometimes developer has to make multiple calls to make these call callbacks they need to be nested which makes it very hard to read and maintain.
The process of nesting callbacks is also referred to as the callback hell which forms the pyramid structure and every callback depends/waits for the previous callback.
It is one of the ways to deal with asynchronous code which cop with the problem of callback hell.
Once a promise is called, it will start in a pending state while the calling function will continue executing, and the promise will reside in a pending state until it resolves. Eventually, the created promise will be ended in resolved or rejected state forward by calling the respective callback function passed to then and catch upon finishing.
Promise chaining is the situation where a promise is returned to another promise which creates a chain of promises.
Async and Await
When there is a long chain of promises just like nested callbacks it gets pretty bulky and confusing. That's why Async and Await were brought about.
Let’s start with the async keyword. It can be placed before a function, like this:
The async function will always return promises, The word “async” before a function means one simple thing: a function always returns a promise.
Await keyword always makes sure a function waits for the promise until it returns its result.
Here’s an example with a promise that resolves in 1 second:
THANKS FOR READING!!