Promise is an important mechanism in JavaScript for handling asynchronous operations, representing the eventual completion or failure of an asynchronous operation. A Promise has three states: pending (in progress), fulfilled (successfully completed), and rejected (failed). Once the state changes, it cannot change again.
Core Concepts
Three States of Promise
- pending: Initial state, neither successful nor failed
- fulfilled: Operation completed successfully
- rejected: Operation failed
Basic Usage
javascriptconst promise = new Promise((resolve, reject) => { // Asynchronous operation setTimeout(() => { if (/* operation successful */) { resolve('Success result'); } else { reject('Failure reason'); } }, 1000); }); promise.then(result => { console.log(result); // Handle success }).catch(error => { console.log(error); // Handle failure });
Promise Chaining
javascriptfetch('/api/user') .then(response => response.json()) .then(user => fetch(`/api/posts/${user.id}`)) .then(response => response.json()) .then(posts => console.log(posts)) .catch(error => console.error(error));
Promise Static Methods
Promise.all(): Returns success only when all Promises succeed, fails if any Promise fails
javascriptPromise.all([promise1, promise2, promise3]) .then(results => console.log(results)) .catch(error => console.error(error));
Promise.race(): Returns the first completed result (whether successful or failed)
javascriptPromise.race([promise1, promise2]) .then(result => console.log(result));
Promise.allSettled(): Waits for all Promises to complete, returns the status of each Promise
javascriptPromise.allSettled([promise1, promise2]) .then(results => console.log(results));
Promise.any(): Returns the first successful Promise
javascriptPromise.any([promise1, promise2]) .then(result => console.log(result));
Common Interview Questions
1. Difference between Promise and Callback
- Promise solves the callback hell problem
- Promise provides better error handling mechanism
- Promise supports chaining, making code clearer
- Promise state is irreversible, more intuitive
2. How to handle Promise errors
Use .catch() method to catch errors, or handle in the second parameter of .then():
javascriptpromise.then( result => console.log(result), error => console.error(error) ); // Or promise.then(result => console.log(result)) .catch(error => console.error(error));
3. Promise Microtask Mechanism
Promise callbacks are microtasks that execute immediately after the current macrotask completes, with higher priority than macrotasks (such as setTimeout).
4. Relationship between async/await and Promise
async/await is syntactic sugar for Promise, making asynchronous code look like synchronous code:
javascriptasync function fetchData() { try { const response = await fetch('/api/data'); const data = await response.json(); return data; } catch (error) { console.error(error); } }
Best Practices
- Always handle errors: Use
.catch()or try/catch - Avoid nested Promises: Use chaining
- Use Promise static methods appropriately: Choose the right method for the scenario
- Understand the event loop: Master the execution order of microtasks and macrotasks
- Performance optimization: Avoid unnecessary Promise wrapping