Node.js › Async Patterns
What is a Promise in JavaScript, and what are its three possible states?
BeginnerAnswer
A Promise is an object representing the eventual result of an asynchronous operation, existing in exactly one of three states at any time: pending (the operation hasn't completed yet), fulfilled (the operation succeeded, with a resulting value), or rejected (the operation failed, with a reason/error) -- once a promise transitions to fulfilled or rejected it is permanently 'settled' and cannot change state again, which is what makes chaining .then()/.catch() predictable.
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
const success = Math.random() > 0.5;
success ? resolve('Data loaded') : reject(new Error('Load failed'));
}, 1000);
});
promise.then(result => console.log(result)).catch(err => console.error(err.message));Real-world example A data-fetching function returns a Promise that resolves with the parsed API response or rejects with a descriptive error, letting every caller consistently use .then()/.catch() or await/try-catch rather than needing to know the internal implementation details of how the request was made.