How To Make Promises In JavaScript

Arvin Fernandez
4 min readJul 11, 2021

--

If you are looking to build applications that interact with API’s you must become familiar with promises. Understanding them allows us to build dynamic UI using JS. Plus it’s not that complicated so you can get to building ASAP.

What Are Promises?

Early implementations of promises and related ideas began to appear as far back as the 1980s. But it wasn’t until 2015 when JavaScript introduced them in ES6.

Promises are objects that eventually(async) settle on a value, much like promises in real life. You might promise your parents that you were going to clean the room. After some time, when your parents come into the room, they will see whether or not you kept your promise.

Promises in JavaScript can either be fulfilled, pending, or rejected. All of them begin in the pending state. After executing whatever was promised, it will settle on either fulfilled where everything works as expected returning the expected value or rejected which means that something went wrong and returns what caused it to be rejected.

How Do Promises Work?

The Promise API gives us access to a bunch of methods but here I will only be covering the most common ones. If you need more in depth information I suggest you checkout the documentation.

To better explain how promises work I will be using a simple example of the promise you made to your parents about cleaning the room.

Just like any other object in JavaScript we have the ability to use the new keyword to create a new instance of a Promise.

const promiseToCleanRoom = () => {
let roomIsClean = false

return new Promise( (resolve, reject) => {
cleanRoom()
})
}

When creating a promise we have the option to pass in a callback which takes two parameters, resolve() and reject() , depending on what happens after executing the promised action. In this case cleanRoom().

Next we must evaluate whether the promise was fulfilled or rejected. This is usually done with conditionals.

const promiseToCleanRoom = () => {
let roomIsClean = false

return new Promise( (resolve, reject) => {
cleanRoom()
if(roomIsClean){
resolve("The room is clean!")
} else{
reject("The room is still dirty")
}
})
}

Both resolve() and reject() can take in anything as an argument, which will then be returned once the promise is settled(either fulfilled or rejected). This function is simply the definition of a promise. For us to use it we must call it and then chain some methods to it.

Because promiseToCleanRoom() will return a promise and promises are asynchronous, meaning that while that function is executing the program will keep on executing the code that follows. For example.

console.log(promiseToCleanRoom())
console.log('Im second but Im first')
// Im second but Im first
// Promise Obj

Notice that its still not returning the desired message though. Thats because the function ultimately returns a Promise regardless of it being resolved or rejected there is an extra step we must take to access those values.

.then

This is a Promise instance method which takes in two callback functions, onFulfilled and onRejected . However, it is not necessary that we pass in both of these arguments.

If our only concern is to handle the fulfilled value we can just pass in a callback which takes in the returned value from the resolve() as an argument.then returns a promise which allows for a chaining of then calls.

.catch

As opposed to .then , this method only handles the rejected cases of the promise. No matter how many then calls are chained to the promise as soon as one is rejected it will fall back to .catch . Sort of a catch all.

If you are looking to handle a specific case, you should pass in both onFulfilled and onRejected callbacks to the .then call you are trying to catch.

You will commonly see these methods structured like this:

fetch(uri)  // fetch() returns a promise
.then(resp => resp.json())
.then(json => display(json))
.catch(error => alert(error))

Conclusion

We learned about promises on a high level but this is more than enough to get our frontend communicating with an API. Here we can see the usefulness of Promises to handle asynchronous operations but their benefits go way beyond that. They can clean up our code from ‘Callback Hell’, handle errors efficiently, and give us the ability to write async code that looks synchronous using async/await . But we’ll talk about that on the next one.

--

--

Arvin Fernandez
Arvin Fernandez

Written by Arvin Fernandez

Junior Developer trying to help other developers(and myself) better understand programming.

No responses yet