Simple Explanation to Callbacks, Promises, and Async Await
Single-threaded means it executes in a sequence, it has one call stack and one memory heap.
But what if a task like calling API or Database, which takes longer time occurs. Will the user have to wait for that task to complete and then only he can move to others.
when execution context finds such code it sends them to the event loop and after execution returns it to the call stack.
Whenever one function has to wait for another function or task to complete Asynchronous functions are used.
So how do these Asynchronous function calls made?
In this article, I am going to cover three ways to implement these Asynchronous functions.
Simple Definition: When a function is passed as an argument to another function it is called Callback
Whenever you need a certain task (e.g: displaying user details after a database query is performed) or function to be executed after a task like API call or a database query or any other calculation is performed then we use a Callback function
By using asynchronous callbacks, you can register action in advance without blocking the entire operation.
Callbacks have a disadvantage called Callback hell where if we need to perform a lot of tasks and function calls when asynchronous tasks complete we need to nest a lot of functions which leads to nested callbacks.
When you nest many callback functions the code becomes difficult to maintain. The solution to this problem is in the next section.
A promise is an object that returns a value that is to be received in the future.
A promise has three states:
- Pending: loading or waiting stage
- Fulfilled: completed the task
- Rejected: error occurred
First, we create a Promise using the Promise Constructor which accepts a function as an argument which is also called the executor. This function also accepts two functions as arguments called ‘resolve’ and ‘reject’.
In the next step, the ‘then()’ method is used to schedule a callback that gets executed when the promise is successfully resolved or rejected. Resolve in case of success and reject it in case of error.
Async/Await was introduced in ES2017 which provides a better way of writing asynchronous code. It is built on top of Promises, so whenever a function returns a Promise you can add the await keyword in front of the function call.
The await keyword can be used only inside the async functions.
Thank You for reading till the end and I hope this article was useful to you. Do follow me for more such Tech Articles. All the Best !!!