Lets's say you have the following code which executes sequentially
This code executes sequentially. But what if you need to perform an operation that depends on data from a server or an API?
Consider the following example where we make an API request using the
This code will fail because the data property does not exist at the time of the console.log() statement. The
axios.get() method returns a Promise, which is an asynchronous operation.
The beauty of Promises is in their methods:
.catch(). The .then() method is used for handling successful responses, while .catch() is used for handling errors.
Async/Await is syntactic sugar over Promises, making asynchronous code easier to write and read. An async function returns a Promise, and the await keyword is used to wait for a Promise to resolve or reject.
This code is more readable and looks synchronous, even though it’s handling asynchronous operations.
Callback Hell typically occurs when you have several nested callbacks, creating a complex and hard-to-read code structure. This often happens when dealing with multiple asynchronous operations that need to be performed in sequence.
Promises provide a cleaner way to handle asynchronous operations. Let’s refactor the above example using Promises:
Async/Await further simplifies asynchronous code, making it even more readable: