βοΈWhat Are JavaScript Promises? Explained with Simple Examples for Beginners
In modern web development, dealing with asynchronous operations is a mustβwhether it’s fetching data from a server or performing a long-running task in the background. That’s where JavaScript Promises come in.
In this blog post, weβll explore JavaScript Promises in simple terms, using real-world analogies and beginner-friendly code examples.
π€ What is a Promise?
A Promise is a JavaScript object that represents the eventual result of an asynchronous operation. It can either:
- β Resolve successfully with a value
- β Reject with an error
Think of it like ordering food: you place an order and receive a “promise” that your meal will arrive. Eventually, the restaurant either brings your food or tells you it’s not available.
π§ How to Create a Promise
Here’s the basic syntax:
javascriptCopyEditlet promise = new Promise(function(resolve, reject) {
// Perform async task
if (/* success condition */) {
resolve("Success!");
} else {
reject("Failure!");
}
});
You handle the result using .then()
and .catch()
:
javascriptCopyEditpromise
.then(result => {
console.log("Resolved:", result);
})
.catch(error => {
console.log("Rejected:", error);
});
β Example 1: Cleaning a Room
javascriptCopyEditlet cleanRoom = new Promise(function(resolve, reject) {
let isClean = true;
if (isClean) {
resolve("The room is clean!");
} else {
reject("The room is messy...");
}
});
cleanRoom
.then(function(message) {
console.log("Promise resolved:", message);
})
.catch(function(error) {
console.log("Promise rejected:", error);
});
Output:
csharpCopyEditPromise resolved: The room is clean!
π Example 2: Simulating a Network Request
javascriptCopyEditfunction fetchData() {
return new Promise((resolve, reject) => {
console.log("Fetching data...");
setTimeout(() => {
let success = true;
if (success) {
resolve({ user: "Alice", age: 25 });
} else {
reject("Failed to fetch data");
}
}, 2000);
});
}
fetchData()
.then(data => {
console.log("Data received:", data);
})
.catch(error => {
console.log("Error:", error);
});
Output:
cssCopyEditFetching data...
Data received: { user: 'Alice', age: 25 }
π Chaining Promises
You can chain multiple .then()
calls to perform sequential actions:
javascriptCopyEditfetchData()
.then(data => {
console.log("User:", data.user);
return data.age;
})
.then(age => {
console.log("Age:", age);
})
.catch(error => {
console.log("Error:", error);
});
π Promise States
A Promise can be in one of three states:
- Pending β still waiting
- Fulfilled β operation completed successfully
- Rejected β operation failed
Once fulfilled or rejected, the state is final and canβt change again.
π Summary
Hereβs a quick overview:
Term | Description |
---|---|
resolve() | Call this when the operation succeeds |
reject() | Call this when the operation fails |
.then() | Handles the success result |
.catch() | Handles any error or rejection |