Promises are used to handle asynchronous operations in JavaScript. A `Promise` is an object representing the eventual completion or failure of an asynchronous operation and its resulting value Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function. - **Benefits of Promises**  1. Improves Code Readability 2. Better handling of asynchronous operations 3. Better flow of control definition in asynchronous logic 4. Better Error Handling ### Consuming a Promise ### How to Create a Promise Create a new instance of the `Promise` object by calling the `Promise` constructor. The constructor takes a single argument: a function called `executor`. The "executor" function is called immediately when the promise is created, and it takes two arguments: a `resolve` function and a `reject` function. ```javascript const myPromise = new Promise(function(resolve, reject) {}); ``` ![[js-promise.png]] ___ A promise has three states: - **Pending:** initial state, neither fulfilled nor rejected. - **Fulfilled:** meaning that an operation was completed successfully. - **Rejected:** meaning that an operation failed. A promise is said to be _settled_ if it is either fulfilled or rejected, but not pending. The methods [`Promise.prototype.then()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then), [`Promise.prototype.catch()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch), and [`Promise.prototype.finally()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally) are used to associate further action with a promise that becomes settled. As these methods return promises, they can be chained. The `.then()` method takes up to two arguments; the first argument is a callback function for the fulfilled case of the promise, and the second argument is a callback function for the rejected case. Each `.then()` returns a newly generated promise object, which can optionally be used for chaining; for example: ### Consume a Promise The return value of each fulfilled promise in the chain is passed along to the next `.then()`, while the reason for rejection is passed along to the next rejection-handler function in the chain. ___ #### More info [Geeks for Geeks](https://www.geeksforgeeks.org/javascript-promises/) [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) ___ **Tags**: #promises