In reality, promises are an easy concept! They’re not as complex as they might seem at first.
In this article you’ll learn what promises are and how you can use them!
So, what are promises? 🤔
A promise object represents the eventual completion or failure of an asynchronous operation.
Simply speaking: a promise is data returned by asynchronous functions.
In the course of its lifetime, a promise can have one of these three states:
- Pending: this is a promise’s initial state
- Fulfilled: the operation was completed successfully
- Rejected: the operation failed (e.g. an error occurred)
After creating a new promise, its state will always be pending. Then you’re able to control the state yourself! By calling
resolve you can fulfill the promise. You could also reject it by using — you guessed it —
Resolve and reject — what does that mean?
As you might have noticed in the code snippet above, the promise constructor takes one single argument. It’s a callback with two parameters,
Both these parameters are functions you can call and pass values to! Let’s take a look at when to call them!
resolvewhen everything went fine and the operation was completed successfully
rejectwhen something didn’t work (e.g. an error occurred) and the promise can’t be fulfilled because of that
Remember I said it’s possible to pass values to
reject? While you can’t pass another promise object, you’re able to pass any other value to these functions!
But what happens with those values after passing them? That’s where notorious
catch come into place.
Quick side note: Don’t forget that execution of the promise still continues after
You most likely don’t want this type of behaviour. But don’t worry, a simple
return statement will do the trick and stop all execution after resolving or rejecting your promise.
One way to run promises is to use
catch. Both functions take a callback as an argument.
Another way, which is a lot more readable, is to make use of
Keep in mind that this method only works inside async functions!
Here’s a fun example!
Let’s imagine you promise to wash the dishes! If they’re clean afterwards, you’ll receive good praise. Should they still be dirty although you promised to wash them… well, they’d still be dirty then!
Feel free to copy this snippet and experiment a little with it! Also, try to create a similar promise by yourself! 🧠
Enough of all these theoretical examples, let’s see a real-world example! 🌍
Chances are, you’ve already worked with the Fetch API. It uses promises, too.
fetch function returns a promise object, on which we can call
- A promise is data returned by asynchronous functions
- When creating a promise yourself: call
resolveif the operation was completed successfully and
rejectin case it failed
- It’s possible to pass any value (except other promise objects) to
- You can execute promises using either
Of course, if you have any questions, don’t hesitate to write a comment! 👍
If you have Instagram, don’t miss my content on there! 🔥