In JavaScript, a Promise is a built-in object that represents the eventual completion (or failure) of an asynchronous operation. It lets you write cleaner, more readable async code compared to traditional callbacks.
Why Use Promises?
Before Promises, asynchronous tasks were handled using callbacks. But nested callbacks—often called “callback hell”—can become messy and hard to manage. Promises solve this by providing a cleaner way to handle asynchronous flow.
Basic Structure of a Promise
const myPromise = new Promise((resolve, reject) => {
// async operation here
if (/* success */) {
resolve("Success!");
} else {
reject("Something went wrong.");
}
});
The Promise constructor takes a function with two arguments:
resolve– called when the task completes successfullyreject– called if there’s an error
Consuming Promises
Once a Promise is returned, you can attach callbacks using .then() and .catch():
myPromise
.then(result => {
console.log("Result:", result);
})
.catch(error => {
console.error("Error:", error);
});
Real-World Example: Fetch API
The fetch() function returns a Promise:
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => {
console.log("Data:", data);
})
.catch(error => {
console.error("Fetch error:", error);
});
Promise States
A Promise can be in one of three states:
- Pending: still in progress
- Fulfilled: successfully completed
- Rejected: failed with an error
Chaining Promises
doSomething()
.then(result => doSomethingElse(result))
.then(finalResult => console.log(finalResult))
.catch(error => console.error(error));
Each .then() returns a new Promise, making it easy to chain multiple async actions.
Async/Await: A Cleaner Way
async function getData() {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
async/await is built on top of Promises and makes your async code look synchronous.
Conclusion
Promises are a modern way to handle asynchronous operations in JavaScript. They make your code cleaner and easier to manage than using nested callbacks. You can use .then(), .catch(), and even async/await to work with Promises effectively.
Post a Comment