Beginner LevelJavaScript & TypeScript
What is the basic syntax and purpose of JavaScript Promises?
❓ Interview Prompt: Explain the three states of a Promise (pending, fulfilled, rejected) and how to handle results with .then(), .catch(), and .finally().
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value.
Three States:
1
Pending: Initial state, neither fulfilled nor rejected.
2
Fulfilled: Operation completed successfully (
resolve(value) was called).3
Rejected: Operation failed (
reject(error) was called).Instance Handlers:
•
`.then(onFulfilled)`: Executed when resolved. Returns a new promise for chaining.
•
`.catch(onRejected)`: Handles any error thrown anywhere in the promise chain.
•
`.finally(onSettled)`: Executes cleanup logic regardless of success or failure.
Code Implementation Example
javascript
function fetchUserData(userId) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (userId > 0) {
resolve({ id: userId, name: 'Alice' });
} else {
reject(new Error('Invalid User ID'));
}
}, 500);
});
}
// Consuming Promise with method chaining
fetchUserData(1)
.then(user => {
console.log('User loaded:', user.name);
return user.id;
})
.catch(err => console.error('Failed:', err.message))
.finally(() => console.log('Fetch attempt complete'));💡Constructing a custom Promise with resolve/reject handlers and chaining .then/.catch.
🎯 Interview Key Takeaway
Promises simplify asynchronous code and eliminate callback hell using .then(), .catch(), and .finally().
#Promises#Asynchronous#Callbacks#Beginner
Back to all JavaScript & TypeScript Questions→