Save it and Thank us Later

Promises in JavaScript are a way to handle asynchronous operations, such as fetching data from a server or reading from a file. There are several methods that can be used on promises to help manage the asynchronous workflow:

  1. then(): This method is used to handle the resolved value of a promise. It takes a callback function that will be executed when the promise resolves successfully. The return value of the callback function will be wrapped in a new promise.
  2. catch(): This method is used to handle errors that occur during the execution of a promise. It takes a callback function that will be executed when the promise rejects. The return value of the callback function will be wrapped in a new promise.
  3. finally(): This method is used to perform cleanup operations, such as closing a database connection or releasing a resource, after a promise settles. It takes a callback function that will be executed regardless of whether the promise resolves or rejects.
  4. Promise.all(): This method is used to handle multiple promises at once. It takes an array of promises and returns a new promise that resolves when all of the input promises have resolved. The resolved values of the input promises are returned as an array.
  5. Promise.race(): This method is used to handle multiple promises at once. It takes an array of promises and returns a new promise that resolves or rejects as soon as one of the input promises resolves or rejects.
  6. Promise.reject(): This method is used to create a new promise that immediately rejects with a specified reason.
  7. Promise.resolve(): This method is used to create a new promise that immediately resolves with a specified value.

By using these methods, you can manage the flow of asynchronous operations in your JavaScript code more effectively and handle errors and cleanup operations in a more organized way.

3 Likes

We can add one more method-
8. Promise.allSettled(): In Promise.all(), if one request is failed then whole promise would get failed. So, to tackle these type of conditions we have Promise.allSettled(). By using this, we can catch failed promises and pass the resolved promises.

2 Likes