Promises
Promise was added to JavaScript in ES6. It was meant to address some of the issues with asynchronous coding, including the callback hell.
A "Promise" is a JavaScript object that holds the eventual result of an asynchronous operation.
A "promise" object has a "state" and its state at any point in time is one of the following:
- Pending: initial state, neither fulfilled nor rejected.
- Fulfilled: meaning that the operation was completed successfully.
- Rejected: meaning that the operation failed.
When you create a Promise
to kick off some asynchronous operation, it is at the pending state. Once the asynchronous operation is completed, the Promise
is fulfilled. If for any reason the asynchronous operations fails (for example, the network connection is disrupted in the middle of a HTTP request), then the Promise
is rejected.
This is the general pattern for creating a Promise
object:
const myPromise = new Promise((resolve, reject) => {
let result = [];
let success = false;
// do some async work!
// success and result must be updated through this work.
if (success) {
resolve(result);
} else {
reject(new Error("some message!"));
}
});
Note the constructor of Promise
takes in a function which itself takes two (callback) functions, resolve
and reject
, as arguments.
Here is how you would consume a promise:
myPromise
.then((result) => {
/* do something with result */
})
.catch((error) => {
/* display the error or otherwise handle it */
});
Notice you have seen this pattern before when we used the fetch
API.
I highly recommend watching Fireship's short YouTube video "JavaScript Promise in 100 Seconds".
The YouTube video JavaScript Promises In 10 Minutes from Web Dev Simplified is another excellent resource.