JavaScript Promises
Promises. I remember it being such a weird concept when I discovered them half a decade ago. I remember reading so many articles but all I could gather from them was either a story about someone promising to come back or the word ‘promise’ repeated over and over again. Somehow, that was supposed to magically make sense.
With a much clearer understanding of the concept now, I’ve decided to give the pesky concept a whirl for developers still trying to wrap their head around the idea.
So let us begin.
What does a promise look like?
//creating the promise
const CoffeeOrder = (data) =>
new Promise((resolve, reject) => {
console.log('2 + 2 - 1 = 3 Quick maths');
//some more code here.
let returnedValue = 'order completed';
resolve(returnedValue);
})
//using the promise
CoffeeOrder(coffeeData)
.then(res => {
console.log(res); //console will log 'order completed'
})
Why do we need promises & how do they work?
Promises are important, especially in the world of asynchronous JavaScript.
asynchronous. adjective. 1. not existing or occurring at the same time. 2. controlling the timing of operations… (dictionary.com)
The idea behind promises is that sometimes, we just need to wait a little bit for things to finish. This may be because we’re using a 3rd party connection or some functions just take longer than expected.
The thing with JavaScript is that it will execute from top to bottom and waits for no one. There is execution context and execution stack…but that’s a completely different story. For now, just know that if you’re still waiting for a reply from your server or API call, your JavaScript has already moved on.
As a result, you might miss out on setting that all important returned value to your local variable. The next thing you know, your entire JavaScript based app has fallen apart.
It’s really no one’s fault. Well, actually, it’s someone’s fault — or else you wouldn’t be having this problem. What if we have a way to tell JavaScript to slow down for a minute and just wait.
That’s what promises do — they tell JavaScript to wait and not do anything until the async call is completed and a value is ‘resolved’.
A 6 step process on how to create a promise:
1. Create the const
to contain your promise
const CoffeeOrder
2. Declare a new promise
const CoffeeOrder = (data) =>
new Promise((resolve, reject) => {})
3. Write whatever code you need to write.
const CoffeeOrder = (data) =>
new Promise((resolve, reject) => {
console.log('2 + 2 - 1 = 3 Quick maths');
//some more code here.
let returnedValue = 'order completed';
})
4. ‘Resolve'
the promise to complete the process or ‘Reject'
to abort the promise and tell the caller that something went wrong.
const CoffeeOrder = (data) =>
new Promise((resolve, reject) => {
console.log('2 + 2 - 1 = 3 Quick maths');
//some more code here.
let returnedValue = 'order completed';
resolve(returnedValue);
})
5. Use the promise however you want by calling it
CoffeeOrder(coffeeData)
6 . then()
at the end of the call to capture the end results.
CoffeeOrder(coffeeData)
.then(res => {
console.log(res); //console will log 'order completed'
})
Bonus step: what if you want to chain several promises together?
Return the promise function and put on another then()
at the end like this:
//calling the CoffeeOrder promise twice
CoffeeOrder(coffeeData)
.then(res => {
return CoffeeOrder(res);
}).then(res => {
console.log(res);
})
Final Words
Promises aren’t that hard once you get the hang of them. Things can get complicated when you start chaining promises together. However, this can create inefficiencies because a promise can only return one object at a time.
A short chain of then()
is not too bad. But if you have 10 or more, things can get real messy and become really slow because you’re waiting for each promise to get resolved. It gets even worse if something breaks in the flow and then we’re back to square one all over again.
There are solutions to this but that’s for another article. Stick around if you want to learn more about the topic.