“Do you promise to buy a black forest cake for my birthday next week?”, your daughter asks.
“Yeah, I promise”, you say.
Promises in JavaScript are like promises in real life—we don’t know if the promise will be fulfilled when it is made.
How a promise works
In JavaScript, a promise is an object that will return a value in future. The promise between you and your daughter will look somewhat like this:
const promise = buyCake('black forest')
We don’t know if you’ll fulfill the promise when you made it. At this point, we say the promise is pending.
Fulfilling a promise
You fulfill your promise to your daughter if you show up with a black forest birthday cake on her birthday. In JavaScript, we say the promise is fulfilled or resolved.
When a promise gets fulfilled, you carry out the next set of instructions in a then method. then takes in a callback that accepts one argument.
buyCake('black forest')
.then(celebrateBirthday)
Some people call promises thenables (then-able) because they have a then method.
Rejecting a promise
If you did not show up with a black forest birthday cake in hand, the promise is not fulfilled. In JavaScript, we say the promise is rejected.
When a promise gets rejected, you perform a contingency plan in a catch method.
You can construct a promise by writing new Promise. Promise here is a constructor (a function that creates other objects). Each constructed promise is a function takes in two values—resolve and reject.
new Promise((resolve, reject) => {
/* Do something here */
})
resolve and reject are functions that take in one value each. If resolve gets called, the promise succeeds and goes into the next then method. If reject gets called, the promise fails and goes into the catch method.
This means you need a condition to determine if a promise resolves or rejects.
new Promise((resolve, reject) => {
if (condition) {
resolve('😁')
} else {
reject('😢')
}
})
// This version is written with ternary operators
new Promise((resolve, reject) => {
condition ? resolve('😁') : reject('😢')
})
In the birthday cake example above, you need to show up with a black forest birthday cake. This is the condition for the promise.
The buyCake promise we built together is a simple one; we resolve or reject the promise immediately without waiting for an actual response from a server.
An example of a real promise is an Ajax call with Fetch.
Fetch and promises
A Fetch request is a promise. You can see it if you log it into the console.