JavaScript 'When Completed' - Understanding Promise Resolution

In JavaScript, promises are a powerful tool for managing asynchronous operations. Understanding how to handle a promise 'when completed' is crucial for writing efficient and reliable code.

What Does 'When Completed' Mean?

When we say a promise is 'completed,' it signifies that the asynchronous operation represented by the promise has finished, either successfully or unsuccessfully.

Promise States:

A promise can be in one of three states:

  1. Pending: The initial state, indicating the operation is in progress.2. Fulfilled: The operation completed successfully.3. Rejected: The operation failed.

Handling Completion with .then() and .catch()

JavaScript provides the .then() and .catch() methods for handling promise resolution:

  • .then(): Executes a callback function when the promise is fulfilled. javascript somePromise .then(result => { // Handle successful completion here console.log('Operation succeeded:', result); });

  • .catch(): Executes a callback function when the promise is rejected. javascript somePromise .catch(error => { // Handle errors here console.error('Operation failed:', error); });

**Example:**javascriptconst fetchData = new Promise((resolve, reject) => { // Simulate an asynchronous operation setTimeout(() => { const data = { message: 'Data fetched!' }; // resolve(data); // Uncomment for successful completion reject('Data fetch failed'); // Comment out for successful completion }, 2000);});

fetchData .then(data => { console.log('Data:', data); }) .catch(error => { console.error('Error:', error); });

Key Points:

  • Promises help manage asynchronous code flow.* .then() handles success, .catch() handles errors. * Understanding promise states is essential for debugging.
JavaScript 'When Completed' - Understanding Promise Resolution

原文地址: https://www.cveoy.top/t/topic/i5H 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录