Promises are simple. You’ve already seen them at work in the Fetch API.
In this chapter, you’re going to learn everything you need to know about promises to use Async JS fluently and effectively.
Let’s go.
What is a Promise?
A JavaScript Promise is like a promise in real life.
Let’s say I promised to buy you a cake for your birthday tomorrow.
My promise can have three states:
- Pending: You don’t know whether I’ll buy a cake yet. You’ll only know when I show up at the party (with or without the cake).
- Resolved or Fulfilled: I showed up with the cake! 🥳
- Rejected: I did not show up with the cake 😞.
A JavaScript Promise has the same three states too:
Pending: Still waiting for resolution or rejectionResolved: Promise is successfully resolvedRejected: Promise is unsuccessful and gets rejected.
To put it simply, a JavaScript promise is an if/else statement that will happen later — you don’t know whether it will be resolved or rejected until that time (or event) comes.
Basic Promise Usage
Here are some rules around using promises.
Handling promise resolution and rejection
All promises have then and catch methods.
- We act on resolved promises in
then. - We can act on rejected promises in
catch.
Let’s say I turned up to the party with the cake. In this case, we get to eat the cake. So eating the cake will take place in the then method.
bringCake().then(cake => eatCake)Now, instead of depending on me to turn up with the cake, you may also have a backup plan (in case I fail to bring the cake).
If I did not show up with the cake, a simple backup plan would be to go and buy a cake together.
bringCake() .then(cake => eatCake) .catch(error => goAndBuyCake) // Promise rejected. Backup plan invokedThen statements can be chained
If you return a value in then, you can use that returned value in the next then.
somePromise() .then(_ => 50) .then(data => console.log(data)) // 50The Fetch API uses this feature since we have to convert the ReadableStream into JSON with response.json.
fetch('https://link-to-resource') .then(response => response.json()) .then(data => {/* do something with data */}Catching Errors
Typically, we will use a catch at the end of the promise chain to handle errors.
We can do this because any errors that occur in a promise will jump straight to the next catch method. It will skip any then methods along the way.
somePromise() .then(face => new Error('🙁')) // Throws an error .then(face => console.log(face)) // Skips this line .catch(face => console.log(face)) // Jumps to this line. Result: Error 🙁Finally
All promises have a finally method. This method will be called after all then and catch calls.
somePromise().then(/*…*/).catch(/*…*/).finally(/*…*/)Personally, I haven’t had much use for the finally method. That said, it’s still good to know this method exists in the event you need it.
The Promise Constructor
You can use the Promise constructor to create a promise.
const promise = new Promise(callback)You don’t need to create promises most of the time. It’s usually meant for advanced use cases (like if you build a wrapper library around the Fetch API 🙃).
So you only have to read this section if you’re interested in a thorough understanding of things.
Creating a promise
Each Promise constructor contains a callback with two arguments — resolve and reject.
const promise = new Promise((resolve, reject) => { // Do something with resolve and reject})Next, we need to determine whether the promise resolves or rejects.
The easiest way is to use an if/else condition in the promise we just created.
- If the condition returns
true, weresolvethe promise. - If the condition returns
false, werejectthe promise.
const promise = new Promise((resolve, reject) => { if (condition) { resolve() } else { reject() }})Both resolve and reject take in a single argument.
- The value passed into
resolvegoes intothen. - The value passed into
rejectgoes intocatch.
const promise = new Promise((resolve, reject) => { if (condition) return resolve('😄') reject('🙁')})
promise() .then(face => console.log(face)) // 😄 .catch(face => console.log(face)) // 🙁 (if rejected)Converting callbacks into promises
You can convert any callback into a promise — because Promises are simply callbacks written in another manner.
But that’s a lesson for another day.
No need to stress yourself trying to understand this right now. Just read this article when you need to do this.
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson