JavaScript Promises

Handling Asynchronous Operations

Promises are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value.

Before Promises, callback functions were used for async operations, often leading to 'callback hell' with nested callbacks.

Promises provide a cleaner way to handle async code with three states: pending (initial), fulfilled (successful), or rejected (failed).

// Creating a Promise
const myPromise = new Promise((resolve, reject) => {
  // Async operation (e.g., fetching data, timer)
  const success = true;

  setTimeout(() => {
    if (success) {
      resolve('Operation successful!'); // Success
    } else {
      reject('Operation failed!'); // Failure
    }
  }, 2000);
});

// Using a Promise
myPromise
  .then(result => {
    console.log(result); // Runs if resolved
    return 'Next step';
  })
  .then(nextResult => {
    console.log(nextResult); // Chain multiple operations
  })
  .catch(error => {
    console.error(error); // Runs if rejected
  })
  .finally(() => {
    console.log('Promise completed'); // Always runs
  });

// Promise.all - Wait for multiple promises
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve) => {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3])
  .then(values => {
    console.log(values); // [3, 42, "foo"]
  });
  • new Promise() - Create a new promise with executor function
  • resolve() - Mark promise as successful with a value
  • reject() - Mark promise as failed with an error
  • .then() - Handle successful promise resolution
  • .catch() - Handle promise rejection (errors)
  • .finally() - Code that runs regardless of outcome
  • Promise.all() - Wait for all promises to complete
  • Promise.race() - Wait for first promise to complete

Try Promises

<div class="promise-demo">
  <h3>Promise Examples</h3>

  <div class="example">
    <h4>1. Simple Promise Timer</h4>
    <button id="startPromise">Start 3-Second Timer</button>
    <div id="promiseStatus">Ready</div>
  </div>

  <div class="example">
    <h4>2. Promise with Success/Failure</h4>
    <button id="successBtn">Resolve Promise</button>
    <button id="failBtn">Reject Promise</button>
    <div id="resultStatus"></div>
  </div>

  <div class="example">
    <h4>3. Promise Chaining</h4>
    <button id="chainBtn">Run Chain</button>
    <div id="chainOutput"></div>
  </div>
</div>

Note: Error Handling: Always include .catch() to handle rejected promises and prevent unhandled promise rejections.

Note: Chaining: Each .then() returns a new promise, allowing you to chain multiple async operations sequentially.

Note: Modern Alternative: async/await (next lesson) provides cleaner syntax for working with promises.