🚀 Introduction
In JavaScript, many operations do not give results immediately. For example, fetching data from a server or reading a file takes time. These operations are called asynchronous operations. To make sure the browser does not freeze while waiting, JavaScript uses special techniques to handle them. Two of the most important techniques are Promises and Async/Await.
🔗 What are Promises?
A Promise in JavaScript is like a container that will eventually hold the result of an asynchronous task. Think of it as a “promise” that something will happen in the future.
- Pending: The task has started but is not finished yet.
- Fulfilled (Resolved): The task finished successfully, and the result is ready.
- Rejected: The task failed, and there is an error message.
Example:
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received successfully!");
}, 2000);
});
fetchData
.then(response => console.log(response))
.catch(error => console.log(error));
👉 Here, the promise waits for 2 seconds and then resolves with a message. If something went wrong, it would go to the catch block.
🧑💻 What is Async/Await?
Async/Await is a simpler and cleaner way of writing code that works with promises. It makes asynchronous code look like normal, step-by-step code.
- The async keyword makes a function always return a promise.
- The await keyword tells JavaScript to wait until the promise is finished (either resolved or rejected).
Example:
async function getData() {
try {
const response = await new Promise((resolve) => {
setTimeout(() => resolve("Data fetched using async/await!"), 2000);
});
console.log(response);
} catch (error) {
console.log(error);
}
}
getData();
👉 This code is easier to read because it looks like synchronous code, but it still works asynchronously.
⚖️ Promises vs Async/Await
📜 Syntax
- Promises: You use .then() to handle the result and .catch() to handle errors.
- Async/Await: You write code that looks synchronous with await, making it easier to follow.
👀 Readability
- Promises: If you need to handle many steps, chaining multiple .then() can become messy and hard to follow (sometimes called “callback hell”).
- Async/Await: Keeps the code simple and clean, especially when dealing with many asynchronous tasks.
🛠️ Error Handling
- Promises: Errors are handled using .catch().
- Async/Await: Errors are handled using try...catch, which is familiar from synchronous code.
⚡ Use Cases
- Promises: Best for running multiple tasks at the same time (like Promise.all for fetching data from many sources together).
- Async/Await: Best when you want to run tasks step by step and need the code to be easy to read.
📘 Best Practices
- Use async/await when you want your code to be more readable and simple.
- Use promises directly when you are handling multiple tasks together.
- Always make sure to handle errors properly, either with .catch() in promises or try...catch in async/await.
📝 Summary
Promises and async/await are two different ways to handle asynchronous operations in JavaScript. Promises let you manage results and errors using .then() and .catch(), while async/await makes the code cleaner and easier to read by using await with try...catch. In short, promises are great when handling multiple tasks together, while async/await is best for writing step-by-step code that is simple to understand.