JavaScript(JS) Promises

h‮sptt‬://www.theitroad.com

JavaScript Promises are a programming construct introduced in ECMAScript 2015 (ES6) to handle asynchronous operations in JavaScript. A Promise is an object representing the eventual completion or failure of an asynchronous operation, and it can be used to manage asynchronous operations in a more readable and maintainable way.

A Promise can be in one of three states:

  1. Pending: The initial state, indicating that the asynchronous operation has not yet completed.
  2. Fulfilled: The state representing that the operation has completed successfully.
  3. Rejected: The state representing that the operation has failed.

Promises can be created using the Promise constructor. The constructor takes a function as its argument, which is called the executor function. The executor function takes two parameters: a resolve function and a reject function. The resolve function is used to fulfill the promise with a value, and the reject function is used to reject the promise with a reason for failure.

Here's an example:

const promise = new Promise((resolve, reject) => {
  // perform an asynchronous operation
  // ...
  if (/* the operation succeeds */) {
    resolve('Operation successful');
  } else {
    reject('Operation failed');
  }
});

Once a Promise is created, we can attach handlers to it using the then and catch methods. The then method is used to handle fulfillment of the Promise, and the catch method is used to handle rejection of the Promise. Both methods return a new Promise, allowing us to chain multiple asynchronous operations together.

Here's an example of how to use then and catch:

promise
  .then(result => {
    console.log(result); // "Operation successful"
  })
  .catch(error => {
    console.error(error); // "Operation failed"
  });

Promises are a powerful tool in JavaScript that allow for more readable and maintainable code when dealing with asynchronous operations.