Promise State and Core Methods

A Promise is an object designed to handle asynchronous operations. It encapsulates asynchronous operations into a single object, allowing for more flexible handling of their results. A Promise object exists in one of three states: pending (waiting), resolved (fulfilled), or rejected. The state can only transition from pending to either resolved or rejected, and once the state is determined, it cannot be changed again.

The primary methods of a Promise object are as follows:

  1. Promise.resolve(value)
    Returns a Promise object in the resolved state, where value represents the result of the Promise.

  2. Promise.reject(reason)
    Returns a Promise object in the rejected state, where reason represents the error cause of the Promise.

  3. Promise.prototype.then(onResolved, onRejected)
    Adds callback functions for both resolved and rejected states. onResolved is used to handle the successful result of the Promise, while onRejected handles the failure reason. This method returns a new Promise object.

  4. Promise.prototype.catch(onRejected)
    Adds a callback function for the rejected state, used to handle the failure reason of the Promise. It returns a new Promise object.

  5. Promise.prototype.finally(onFinally)
    Adds a callback function that executes regardless of whether the Promise object is resolved or rejected. It returns a new Promise object.

const promise = new Promise((resolve, reject) => {
  // Execute asynchronous task
  // ...
  // After the asynchronous task completes, call resolve or reject method
  if (success) {
    resolve(data);
  } else {
    reject(error);
  }
});

promise.then(data => {
  // Use data returned by the asynchronous task
  // ...
})
.catch(error => {
  // Handle errors from the asynchronous task
  // ...
})
.finally(() => {
  // Callback function that executes regardless of the Promise object's state
  // ...
});

In summary, a Promise object is an object designed to handle asynchronous operations. It encapsulates asynchronous operations into a single object, enabling more flexible handling of their results. The state of a Promise object can only transition from pending to resolved or rejected, and once the state is determined, it cannot be changed again. The primary methods of a Promise object include resolve, reject, then, catch, and finally. The most suitable method should be selected based on specific requirements and actual scenarios.