Promise in JavaScript
What is a Promise in JavaScript? π€
A Promise in JavaScript is like a real-life promise:
π "I promise I'll finish my homework."
If you finish it, promise is fulfilled (resolved).
If you don't, promise is broken (rejected).
How Do Promises Work in Code?
A Promise has three states:
1οΈβ£ Pending β Waiting for something to happen.
2οΈβ£ Resolved (Fulfilled) β Everything went fine. β
3οΈβ£ Rejected β Something went wrong. β
Example 1: Creating a Simple Promise
let myPromise = new Promise((resolve, reject) => {
let homeworkDone = true; // Change this to false to see rejection
if (homeworkDone) {
resolve("I finished my homework! π"); // Success
} else {
reject("I didn't do my homework. π’"); // Failure
}
});
// Using the Promise
myPromise
.then((message) => console.log("Success:", message)) // If resolved
.catch((error) => console.log("Error:", error)) // If rejected
.finally(() => console.log("Promise finished.")); // Always runs
Why Do We Use Promises?
Promises help handle tasks that take time, like:
β
Fetching data from a server
β
Reading a file
β
Waiting for a user action
Without Promises, JavaScript would execute everything at once, even if some tasks arenβt finished.
Example 2: Using a Promise with setTimeout (Simulating Delay)
let delayedPromise = new Promise((resolve, reject) => {
console.log("Loading... β³");
setTimeout(() => {
let success = true; // Try changing to false
if (success) {
resolve("Data loaded successfully! π");
} else {
reject("Failed to load data. β");
}
}, 3000); // Wait 3 seconds
});
delayedPromise
.then((message) => console.log("Success:", message))
.catch((error) => console.log("Error:", error))
.finally(() => console.log("Process completed."));
π The program waits 3 seconds before resolving or rejecting.
Example 3: Fetching Data with Promises
Now, letβs use fetch(), which returns a Promise automatically.
fetch("https://jsonplaceholder.typicode.com/users/1")
.then((response) => response.json()) // Convert response to JSON
.then((data) => console.log("User:", data)) // Success case
.catch((error) => console.log("Error:", error)) // Failure case
.finally(() => console.log("Request finished."));
π If the request succeeds, .then() runs.
π If it fails, .catch() runs.
π .finally() always runs, no matter what happens.
Example 4: Using Promise.all() (Handling Multiple Promises at Once)
Sometimes, you need to run multiple Promises together and wait for all of them.
let promise1 = fetch("https://jsonplaceholder.typicode.com/users/1").then(res => res.json());
let promise2 = fetch("https://jsonplaceholder.typicode.com/users/2").then(res => res.json());
Promise.all([promise1, promise2])
.then((results) => console.log("Both users:", results))
.catch((error) => console.log("Error:", error));
π If both requests succeed, .then() runs with an array of results.
π If one fails, .catch() runs.
Summary (TL;DR)
β
Promises handle things that take time.
β
They have three states: Pending, Resolved, Rejected.
β
Use .then() for success and .catch() for errors.
β
Use .finally() to run something at the end.
β
Use Promise.all() to wait for multiple Promises.
Next Steps?
Now that you understand Promises, you can learn async/await, which makes Promises even easier to work with.