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)