What is the purpose of ‘new Promise’ in ES6?

The new Promise() in ES6 is used to create a new Promise object.

A Promise is a way to deal with asynchronous operations, where these operations can be encapsulated into a Promise object to easily handle success, failure, and state changes.

The constructor of new Promise() takes a function as a parameter, which has two arguments: resolve and reject. Within this function, asynchronous operations can be performed and the Promise object’s state can be changed by invoking resolve or reject based on the result of the operation.

  1. If the asynchronous operation is successfully completed, the resolve function can be called to change the Promise object’s status to fulfilled and pass the operation result as a parameter.
  2. If an asynchronous operation fails or encounters an error, you can use the reject function to change the status of the Promise object to rejected, and pass an error message or error object as a parameter.

The Promise object created through new Promise() can be handled using the .then() and .catch() methods to deal with the success and failure of the operation.

  1. The .then() method takes a callback function as a parameter, which is called when the Promise object is fulfilled, passing the result of the operation as an argument to the callback function.
  2. The .catch() method takes a callback function as a parameter. When the Promise object’s status changes to rejected, it calls that callback function and passes the error message or error object as a parameter to the callback function.

Using Promises allows for a clearer handling of the results of asynchronous operations, and you can achieve the sequential execution of multiple asynchronous operations by chaining the .then() method.

bannerAds