乐闻世界logo
搜索文章和话题

What is a Promise? What are the states of a Promise?

2月22日 14:08

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

javascript
const 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

javascript
fetch('/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

javascript
Promise.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)

javascript
Promise.race([promise1, promise2]) .then(result => console.log(result));

Promise.allSettled(): Waits for all Promises to complete, returns the status of each Promise

javascript
Promise.allSettled([promise1, promise2]) .then(results => console.log(results));

Promise.any(): Returns the first successful Promise

javascript
Promise.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():

javascript
promise.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:

javascript
async function fetchData() { try { const response = await fetch('/api/data'); const data = await response.json(); return data; } catch (error) { console.error(error); } }

Best Practices

  1. Always handle errors: Use .catch() or try/catch
  2. Avoid nested Promises: Use chaining
  3. Use Promise static methods appropriately: Choose the right method for the scenario
  4. Understand the event loop: Master the execution order of microtasks and macrotasks
  5. Performance optimization: Avoid unnecessary Promise wrapping
标签:Promise