DEV Community


Posted on


What is a Promise?!?


Promises have had me head scratching for quite a while but now I feel I have a grasp of what they are and how to use them I thought why not create a post for others who may of felt the same.

The definition

I will start with the definition given by Javascript MDN:

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

What I took from this is that it is very similar to how we think of a normal promise, someone promises to do something for you when he/she gets something from you.

For instance I can promise to give you some data in turn of you giving me the location to find it. Now I can hold this promise if data is in the location you provided or reject if the data you asked for isn't at the provided

Javascript promises work in a very similar way, they will return a resolve or a reject. The resolve will hold the information that you expect when from the function and the reject will usually hold the error or why the promises couldn't be held.

Note: It is always good to know what type of data type you are expecting back from a promise.

I will now show a simple promise which I have written up:

This promise will resolve if I give the parameter name as 'Lewis' or reject if it is not.

Alt Text

We then can run this promise by simply calling the function and chaining a .then() to it. This then allows you to pass the data through and then do some computational stuff with (You can chain .then() together which I will show later on). There is also a .catch() which is used to hold the errors if the promise returns a reject. There is usually one catch per promise as they can catch all errors.

Alt Text

The following promise will result in the following code.

Alt Text

And if I give the wrong name I get the rejection error (the catch) executed.

Alt Text

Alt Text

Getting data example

I have another example which is similar to my analogy above:

Alt Text

I have created above a promise that will read data from a text file using a node module.

I then chain multiple .then() together to get the edit the data I get back from the promise.

Alt Text

Which outputs:

Alt Text

Why use them

The advantages of using promises are you are able to chain them together using the .then() and catch errors using the .catch() which helps avoid callback hell. Also it is much easier to follow what the code is doing and each point.

You can also use async await which is syntactical sugar to make promises even easier to read!

I hope this aided you in getting a better understanding of Javascript Promises

Thank you

I'm open to comments about this little description as I am new to blog posts.

Top comments (0)

Visualizing Promises and Async/Await 🤓

async await

☝️ Check out this all-time classic DEV post on visualizing Promises and Async/Await 🤓