Handling Asynchronous Operations the Right Way
JavaScript is single-threaded, but it can handle asynchronous operations like API calls, file reading, and timers.
To manage these async tasks efficiently, JavaScript provides Promises.
🔹 What is a Promise in JavaScript?
A Promise is an object that represents the eventual completion or failure of an asynchronous operation.
In simple words:
👉 “I promise to return a value later — either success or error.”
🔹 Why Do We Need Promises?
Before Promises, JavaScript used callbacks, which caused problems like:
❌ Callback Hell
❌ Hard-to-read code
❌ Difficult error handling
Promises solve these problems by providing:
- Cleaner syntax
- Better error handling
- Chainable operations
🔹 Promise States
A Promise can be in one of three states:
- Pending – Initial state (waiting)
- *Fulfilled *– Operation completed successfully
- Rejected – Operation failed
Once a promise is fulfilled or rejected, it is settled and cannot change again.
🔹 Creating a Promise
`const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Promise resolved successfully");
} else {
reject("Promise rejected");
}
});
- resolve() → success result
- reject() → error result`
🔹 Consuming a Promise
`Using .then() and .catch()
myPromise
.then(result => {
console.log(result);
})
.catch(error => {
console.log(error);
});
- .then() → handles success
- .catch() → handles error`
🔹 Promise Chaining
Promises can be chained to **perform multiple async tasks **sequentially.
fetchData()
.then(data => processData(data))
.then(result => displayResult(result))
.catch(error => console.log(error));
✅ Avoids callback hell
✅ Improves readability


Top comments (0)