Introduction to Promises
Promises are a fundamental concept in JavaScript that allows you to handle asynchronous operations in a more elegant and efficient way. In this article, we will explore the basics of promises, how they work, and provide examples of their usage.
A Promise is a JavaScript object that represents the eventual completion (success) or failure of an asynchronous operation — and lets you handle the result later.
It’s like a placeholder for a value that is not yet available but will be resolved in the future.
Example:-
let promise = new Promise(function(resolve, reject) {
// async task...
if (success) {
resolve(result); // task finished successfully
} else {
reject(error); // task failed
}
});
States of a Promise
State |
Description |
pending |
Initial state — not fulfilled or rejected |
fulfilled |
Operation completed successfully |
rejected |
Operation failed |
Consuming a Promise
ou are waiting for the result of an asynchronous operation and handling what happens next — whether it succeeds or fails.
Resolved: the task is successful .then() is triggered.
Rejected: the task fails .catch() is triggered.
promise
.then(function(result) {
// handles success
})
.catch(function(error) {
// handles failure
});
Example: Creating and Using a Promise
function orderPizza() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const available = true;
if (available) {
resolve("Pizza is ready!");
} else {
reject("Pizza shop is closed.");
}
}, 2000);
});
}
// Consume the promise
orderPizza()
.then((message) => {
console.log("Success:", message);
})
.catch((error) => {
console.log("Error:", error);
});
Why use Promise
Feature |
Benefit |
Handles async code |
Waits for future tasks to finish |
Cleaner than callbacks |
Avoids callback hell |
Chainable |
.then() and .catch() make code easier to read |
Works with async/await |
Enables modern syntax and structure |