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
- Create a Promise:
javascript const fetchData = new Promise((resolve, reject) => { setTimeout(() => resolve("data"), 1000); }); - Chain handlers:
javascript fetchData .then(data => console.log(data)) .catch(err => console.error(err)) .finally(() => console.log("Done")); - Chain multiple asynchronous operations:
javascript getUser() .then(user => getOrders(user.id)) .then(orders => console.log(orders)) .catch(err => console.error(err)); - Use
Promise.allto 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.allSettledwhen 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.