JS Promises

Skabe89
2 min readSep 9, 2021

A promise in JS a lot like a promise in real life. If you tell someone ‘I promise to call you back within five minutes’ there are basically only two outcomes, you either call them back when you said you would or you don’t. That’s a lot like promises in JS. A promise in JS can have three states; ‘pending’ (the time between when you gave your promise to call back and the 5 minute cut off), ‘fulfilled’ (you actually called them back within 5 minutes!), and ‘rejected’ (tsk tsk…you didn’t call back). To demonstrate our promise open up a coding editor or sandbox to follow along! (https://codepen.io/)

let call = trueconst p = new Promise((resolve, reject) => {
if(call){
resolve('Thanks for calling me back!')
}
else{
reject('BOOOOOO!')
}
})

First, we set a variable ‘call’ to true. Then we set a variable ‘p’ to a new promise object. In our new promise we are defining a function that takes two functions as arguments, ‘resolve’ and ‘reject’. At this point we can make a conditional statement of if they called back within 5 minutes, and send a message of ‘Thanks for calling me back!’ through the resolve function. If ‘call’ is not true, we send the message ‘BOOOOOOO!’ through the reject function.

Now that we have the promise defined, we can call on the promise with the .then() method.

let call = trueconst p = new Promise((resolve, reject) => {
if(call){
resolve('Thanks for calling me back!')
}
else{
reject('BOOOOOO!')
}
})
p.then(message => {
console.log(message)
}).catch(error => console.log(error)
})

If you’ve ever used ‘fetch’ this will probably look very familiar. The ‘.then()’ method will return the what our ‘resolve’ condition is set to while ‘.catch’ will handle our error. If you’ve followed along, your console should log out the ‘Thanks for calling me back!’. Now watch what happens when you change ‘call’ to equal false. Our promise will return the ‘BOOOOOOO!’ message just like we expected.

While I’ve used JS promise plenty of times, I never took the time to appreciate what was happening behind the scenes until I wrote a couple of promises myself like this. I hope this has shined a light on what’s happening with those promises during a fetch for you!

--

--