Problem Statement
What are the three states of a Promise?
Explanation
A Promise has three states:
Pending is the initial state. The operation has started but not completed yet.
Fulfilled means the operation completed successfully. The promise has a resolved value.
Rejected means the operation failed. The promise has a rejection reason or error.
Once a promise is fulfilled or rejected, it stays in that state forever. It cannot change again.
Promises are used to handle asynchronous operations in a cleaner way than callbacks.
Code Solution
SolutionRead Only
// Creating a Promise
const myPromise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve('Operation successful!'); // Fulfilled
} else {
reject('Operation failed!'); // Rejected
}
});
// Using the Promise
myPromise
.then(result => {
console.log(result); // 'Operation successful!'
})
.catch(error => {
console.log(error);
});
// Real example - simulating API call
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = {name: 'John', age: 30};
resolve(data); // Fulfilled after 1 second
}, 1000);
});
}
fetchData()
.then(data => {
console.log('Data received:', data);
})
.catch(error => {
console.log('Error:', error);
});
// Chaining promises
fetchData()
.then(data => {
console.log('First then:', data);
return data.name;
})
.then(name => {
console.log('Second then:', name);
})
.catch(error => {
console.log('Error:', error);
})
.finally(() => {
console.log('Always runs');
});