A JavaScript Promise is an **object** that can be used to get the outcome of an asynchronous operation when that result is not instantly available.
They're used to handle asynchronous operations in JavaScript.
Promises exist in JavaScript because we need callbacks. We need callbacks because JavaScript is single-threaded and can’t wait around for things.
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
A promise has three states:
- **Pending:** initial state, neither fulfilled nor rejected.
- **Fulfilled:** The operation has completed successfully and the promise now has a _resolved value_.
- **Rejected:** The operation has failed and the promise has a reason for the failure. This reason is usually an `Error` of some kind.
A promise is said to be _settled_ if it is either fulfilled or rejected, but not pending.
All promises eventually settle, enabling us to write logic for what to do if the promise fulfills or if it rejects.
### How to Create a Promise
Create a new instance of the `Promise` object by using the `new` keyword and 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.
![[js-promise.png]]
- `resolve` is a function with one argument.
- Under the hood, if invoked, `resolve()` will change the promise’s status from `pending` to `fulfilled`, and the promise’s resolved value will be set to the argument passed into `resolve()`.
- `reject` is a function that takes a reason or error as an argument.
- Under the hood, if invoked, `reject()` will change the promise’s status from `pending` to `rejected`, and the promise’s rejection reason will be set to the argument passed into `reject()`.
```javascript
const executorFunction = (resolve, reject) => {
if (1 + 1 === 2) {
resolve('I resolved!');
} else {
reject('I rejected!');
}
};
const myFirstPromise = new Promise(executorFunction);
myFirstPromise //➞ Promise { 'I resolved!' }
```
In the example above, `executorFunction` resolves or rejects based on a simple condition; *in practice, however, promises settle based on the results of asynchronous operations.* For example, a database request may fulfill with the data from a query or reject with an error thrown.
___
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