A Promise of Future Data

A Promise is an object that represents the eventual result of an asynchronous operation. Think of it as a " receipt " — it doesn't give you the data immediately, but it guarantees you'll get a result (or an error) eventually.

The Three States of a Promise

  • pending: The initial state — the operation is still in progress.
  • fulfilled: The operation completed successfully. The promise has a result value.
  • rejected: The operation failed. The promise has an error reason.

Once a promise moves from pending to either fulfilled or rejected, it is settled and cannot change state again.

Creating a Promise

let promise = new Promise(function(resolve, reject) {
  // This "executor" function runs immediately

  setTimeout(() => {
    // Simulate an async operation finishing after 1 second
    resolve('Data loaded successfully!');
    // OR if something went wrong:
    // reject(new Error('Loading failed!'));
  }, 1000);
});

Consuming the Result

promise
  .then(result => console.log(result)) // Runs on success
  .catch(error => console.error(error)); // Runs on failure
Important

Use .then(f) if you only care about success. Use .catch(f) if you only care about failure. For cleanup that should always run (like hiding a loading spinner), use .finally(f).