Back to results for “Error Handling”
Node.js › Async Patterns

What is a Promise in JavaScript, and what are its three possible states?

Beginner

Answer

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.

Common follow-ups: What happens if resolve() is called after reject() has already been called on the same promise?;How does Promise.prototype.finally() differ from adding logic inside both .then() and .catch()?