What is a Promise - paulip114/blog GitHub Wiki

โœ… What is a Promise?

A Promise is a JavaScript object that represents the eventual result (or failure) of an asynchronous operation.

Think of it like a "contract" for a future valueโ€”something that hasnโ€™t happened yet, but will.


๐Ÿง  Analogy:

Imagine you order food online. You get a "promise" that it will arrive.
While you're waiting, you can keep doing other things.
Later, the food will either be:

  • Delivered โœ… (fulfilled),
  • Canceled โŒ (rejected), or
  • Still on the way (pending...).

๐Ÿ“ฆ States of a Promise

A Promise has three states:

State Meaning
pending The operation is still in progress
fulfilled The operation completed successfully
rejected The operation failed with an error

โœ๏ธ Syntax

const promise = new Promise((resolve, reject) => {
  // async task
  if (success) {
    resolve(result); // fulfilled
  } else {
    reject(error);   // rejected
  }
});

๐Ÿ”„ Handling Promises

promise
  .then(result => {
    // handle success
  })
  .catch(error => {
    // handle error
  });

๐Ÿ•’ Example: Delay with setTimeout

function wait(ms) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("Done waiting");
    }, ms);
  });
}

wait(1000).then(msg => {
  console.log(msg); // "Done waiting" after 1 second
});

โœ… Why use Promises?

  • They make asynchronous code more manageable.
  • Replace callback hell.
  • Work well with async/await syntax.

๐Ÿ” Bonus: async / await (syntactic sugar for Promises)

async function example() {
  const msg = await wait(1000);
  console.log(msg);
}