When I started learning JavaScript, I learned about variables, functions, arrays, and DOM manipulation. Then I came across Promises.
At first, Promises looked confusing, but simple examples helped me understand them.
What is a Promise?
A Promise is a JavaScript object that represents the eventual success or failure of an asynchronous operation.
For example, imagine ordering food online 🍕. Your order may be accepted, rejected, or still processing.
Promises have three states:
Pending – The operation is still in progress.
Fulfilled – The operation completed successfully.
Rejected – The operation failed.
Creating a Promise
Let's create a simple Promise.
let myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Task completed!");
} else {
reject("Task failed!");
}
});
Here:
resolve() indicates success.
reject() indicates failure.
Using .then() and .catch()
We can handle the result of a Promise using .then() and .catch().
myPromise
.then(result => {
console.log(result);
})
.catch(error => {
console.log(error);
});
Output:
Task completed!
.then() handles successful completion.
.catch() handles errors.
Promise with setTimeout()
Let's simulate a task that takes two seconds.
let task = new Promise((resolve) => {
setTimeout(() => {
resolve("Data loaded successfully!");
}, 2000);
});
task.then(result => console.log(result));
The message appears after two seconds.
Using Promises with the DOM
Now let's display the result on a webpage.
<h2 id="message">Loading...</h2>
let message = document.getElementById("message");
function loadData() {
return new Promise(resolve => {
setTimeout(() => {
resolve("Welcome to JavaScript!");
}, 2000);
});
}
loadData().then(result => {
message.textContent = result;
});
Here, the DOM displays Loading... first and updates the text after two seconds.
This demonstrates how Promises and DOM manipulation can work together.
Why Are Promises Useful?
Promises are commonly used for:
Fetching data from APIs
Loading information from a server
Handling asynchronous operations
Managing success and error responses
Conclusion
Promises help us handle operations that don't finish immediately. Understanding resolve(), reject(), .then(), and .catch() is a great first step toward learning asynchronous JavaScript.
Learn → Practice → Build → Improve! 🚀
Top comments (0)