Category: javascript
JS Promise
Published on 18 Feb 2026
Explanation
A Promise in JavaScript is an object that
represents the eventual completion or
failure of an
asynchronous operation.
Code:
let promise = new Promise((resolve, reject) => {
resolve("Success");
});
console.log(promise);
Explanation
A Promise has three states: Pending (initial state),
Fulfilled (operation successful), and Rejected (operation failed).
Code:
#white-// Pending -> Initial state #white-// Fulfilled -> resolve() called #white-// Rejected -> reject() called
Explanation
The then() method is used to handle the
result when a Promise is fulfilled.
Code:
let promise = new Promise((resolve) => {
resolve("Data received");
});
promise.then(result => console.log(result));
Explanation
The catch() method is used to handle errors
when a Promise is rejected.
Code:
let promise = new Promise((resolve, reject) => {
reject("Error occurred");
});
promise.catch(error => console.log(error));
Explanation
Promises are commonly used for
asynchronous tasks like
API calls or delayed operations.
Code:
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data loaded");
}, 2000);
});
}
fetchData().then(data => console.log(data));
Explanation
Promises can be chained using multiple then() methods
to perform sequential asynchronous operations.
Code:
Promise.resolve(5) .then(num => num * 2) .then(result => console.log(result));