Promises are very similar to a promise in real life, they can be kept or broken. Promise object is data returned by asynchronous function. It can be a **resolve** if the function returned successfully or a **reject** if function returned an error.
A Promise is in one of these states:
- Initial state, neither fulfilled or rejected - _pending_
- The operation completed successfully - _fulfilled_
- The operation failed - _rejected_
This is how a promise is created:
```
var promise = new Promise(function(resolve, reject){
/* executor */
});
```
The function that is passed to new Promise is called executor and takes two parameters,
resolve and reject (also functions). The resolve and reject functions, when called,
resolve or reject the promise, respectively. When the promise is created, this executor
function runs automatically.
Here is an example with a simple _setTimeout_ function:
```
var promise = new Promise(function (resolve, reject) {
setTimeout(() => resolve("done!"), 2000);
});
```
After two seconds of processing the executor calls resolve(“done!”), to produce the
results from “pending” (results = undefined) to resolved(result=“done”) and since
it’s resolved it has “fulfilled” the promise. Here is an example of the executor
rejecting the promise with an error:
```
var promise = new Promise(function (resolve, reject) {
setTimeout(() => reject(new Error("fail!"), 2000);
});
```
The executor does a job, usually something that takes time, and than calls reject or
resolve to change the state of the promise object. The executor should only call
resolve or reject once, the promise’s state is final and further calls will be
ignored. Promises can give us flexibility and better code flow. To summarize,
the promise object represents the completion or failure of an asynchronous
operation and its resulting value.