How to use Promises in JavaScript

· Category: JavaScript

Short answer

A Promise represents a value that may not exist yet but will resolve or reject at some point in the future. Use .then() for success, .catch() for errors, and .finally() for cleanup.

Steps

  1. Create a Promise: javascript const fetchData = new Promise((resolve, reject) => { setTimeout(() => resolve("data"), 1000); });
  2. Chain handlers: javascript fetchData .then(data => console.log(data)) .catch(err => console.error(err)) .finally(() => console.log("Done"));
  3. Chain multiple asynchronous operations: javascript getUser() .then(user => getOrders(user.id)) .then(orders => console.log(orders)) .catch(err => console.error(err));
  4. Use Promise.all to run tasks in parallel: javascript Promise.all([fetchA(), fetchB()]) .then(([a, b]) => console.log(a, b));

Tips

  • Always return values in .then() to pass them down the chain.
  • Use Promise.allSettled when you need results from all promises regardless of rejection.

Common issues

  • Forgetting to return a Promise inside .then() breaks the chain.
  • Unhandled rejections crash Node.js or log warnings in browsers.