Skip to content
Home » Blog » Learn how to use Promises in JavaScript

Learn how to use Promises in JavaScript

INTRODUCTION TO PROMISES

What are promises? In this article you will learn about promises in javascript, the functionalities of promises, and how to implement it in JavaScript. So you do need to know you should know the basics like variables and functions. Also you should also learn about something called Callback functions and Callback Hell in JavaScript. Another thing that you should learn are arrow/anonymous functions, as you will use it in promises. Input functions like onclick, oninput will also help you understand the example. Classes will also be required as it will help you understand the Promise syntax much much better.

If you do not know what JavaScript is this link should help: JavaScript

Now lets answer what promises are. Promises in coding are similar to promises in the real world. First you make a promise, then you could either resolve the promise or you could reject the promise made. In coding however you can implement certain code, which will be executed if it is resolved. Or other code when rejected.

Ok now that the introduction is over, lets look at the syntax of a promise.

SYNTAX

Now lets look at how the syntax of promises in JavaScript looks like in irl (in real life) code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Promises Syntax</title>
</head>
<body>

    <script src="scripts.js"></script>
</body>
</html>

This is just a simple HTML boiler plate, which is connected to the scripts.js (which will be shown below) using the script tag.

wentToGym = true

const p = new Promise((resolve, reject) => {
    if(wentToGym){
        resolve("went to gym")
    } else {
        reject("did not go to gym")
    }
})

p.then((msg) => {
    console.log("User " + msg)
})  .catch((msg) => {
    console.log("User " + msg)
})  .finally(() => {
    console.log("User then ate lunch")
})

This is where the syntax of a promise is shown.

1: In this line, I set the variable: wentToGym to true, the variable is a Boolean which is either true or false.

3-9: These lines will be where the promise is held, first you set a constant variable to the instance of the Promise object using the new keyword, we are naming this variable: p, then inside the Promise parenthesis, we will send an arrow function as an argument, in the function parenthesis we have two arguments, the 1st on is resolve, which is the function that will resolve the promise, and the 2nd one, reject, which is the function that will reject said promise. Now if the variable wentToGym is true, then we will resolve the promise with an argument: “went to gym”, but if it is false, we will reject the promise with an argument: “did not go to gym”.

11-12: Now the 1st line, I wrote p.then(), this means that if the promise is resolved, the code in the arguments’ arrow function will be executed, in the arrow function I receive the argument in which I called msg, which is the argument received from the resolve function in the Promise, in the next line I just log the message given.

13-14: This is the same thing except now we are logging the rejected argument, this is happening in the .catch() function.

15-17 The finally function is execute after either the promise is resolved or rejected, the finally function is executed no matter what, here I just logged the following: “User then ate lunch”

HOW IT LOOKS

Ok sweet, now lets look how the syntax of promises in JavaScript looks and works:

First to look at the Console you have to type the key combination: ctr+shift+i. Then click on the console tab, which will be right next to the Elements tab

If the variable, wentToGym is true, then the following will show:

Else if the variable, wentToGym is false, then it will show the following:

Now lets look at an example of a promise.

EXAMPLE OF A PROMISE

Great now lets look at an example of promises in JavaScript. Though looking at the explanation first is recommended as it will help you understand said example of a promise:

The promise is that I have to go to the gym. Now I can resolve or reject the promise. Resolving the promise will mean that I will go to the gym today. But if I reject the promise, I will not go to the gym. The green button indicates that I wish to resolve said promise and go to the gym. Whereas the red button indicates that I wish to reject the promise and not go to the gym.

RESOLUTION OF A PROMISE

First lets see what happens if I resolve the promise:

As you can see above when I click the green button it shows the text in green.

REJECTION OF A PROMISE

Now lets see how the promise works if the red button is clicked:

When the red button is pressed the text in red is shown.

Now lets move on to the source code.

SOURCE CODE

Ok now, lets move on to the source code of the example of promises in JavaScript shown above:

INDEX.HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Promises Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <p class="text">I promise to go to the gym today</p>
    <button class="resolve" onclick="promiseCheck('I will go to gym')">Resolve Promise</button>
    <button class="reject" onclick="promiseCheck('I will not go to gym')">Reject Promise</button><br>
    <p class="text" id="txt"></p>
    
    <script src="scripts.js"></script>
</body>
</html>

STYLES.CSS

body {
    background-color: rgba(0, 0, 0, 0.826);
    text-align: center;
}

button.reject {
    margin-top: 10px;
    color: wheat;
    background-color: red;
    border-color: darkred;
    width: 300px;
    height: 150px;
    font-size: 50px;
}

button.resolve {
    margin-top: 10px;
    color: wheat;
    background-color: green;
    border-color: darkgreen;
    width: 300px;
    height: 150px;
    font-size: 50px;
}

p.text {
    font-size: 50px;
}

SCRIPTS.JS

function promiseFunc(choice) {
    return new Promise((resolve, reject) => {
        if(choice === "I will go to gym"){
            resolve("promise has been resolved")
        }
        else {
            reject("promise had been rejected")
        }
    })
}

function promiseCheck(myChoice) {
    promiseFunc(myChoice).then((msg) => {
        document.getElementById("txt").innerText = 
            "I will go to gym because " + msg

        document.getElementById("txt").style.color = "green"

    })  .catch((msg) => {
        document.getElementById("txt").innerText = 
            "I will not go to gym because " + msg

        document.getElementById("txt").style.color = "red"
    })

}

EXPLAINATION

If you did not understand the source code by just looking at it, the explanation will help a ton.

INDEX.HTML

This is the HTML file in which we create the webpage:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Promises Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <p>I promise to go to the gym today</p>
    <button>Resolve Promise</button>
    <button>Reject Promise</button><br>
    
    <script src="scripts.js"></script>
</body>
</html>

4: The title tag is used to show the title of the tab in the browser.

5: Link tag is used to link the HTML file to the CSS stylesheet file, we will call it styles.css.

8: Will show what we are promising to do, in this case we are promising to: “I promise to go to the gym today”.

9-10: These are the buttons which will be pressed if the promise is rejected or resolved, respectively.

12: Script tag is used to connect the scripts.js which is our JavaScript file to index.html, which is our html file.

Ok lets move on to the styling, which will be in the, styles.css, CSS file:

STYLES.CSS

* {
    font-size: 50px;
}

body {
    background-color: rgba(0, 0, 0, 0.826);
    text-align: center;
}

button.reject {
    margin-top: 10px;
    color: wheat;
    background-color: red;
    border-color: darkred;
    width: 300px;
    height: 150px;
}

button.resolve {
    margin-top: 10px;
    color: wheat;
    background-color: green;
    border-color: darkgreen;
    width: 300px;
    height: 150px;
}

1-3: * means everything, this means everything in the html page will have a font size of: 50px (pixels), and centered text by using the text-align: center;

6-7: The body tag is used to set the background color to: rgba(0, 0, 0, 0.826). I used the body tag instead of *, because * will set every tag’s background color to said color.

10-16: The code: button.reject, means that the reject is a class, in which we can add as an attribute to a button tag, and all of the styles in the button.reject will be used in the said button class. We set the margin-top to 10px, margin is the space between the object and whatever is outside object. The font color is; wheat, and the background color to red, the border-color of the button will be set to dark red (darkred). The width of the button is 300px and the height of the button is 150px. This styling will be used on the reject button.

19-15: This will have the exact styling we did with button.reject, except instead of button.reject, we will have button.resolve, and the background color will be green and the border color will be dark green (darkgreen).

INDEX.HTML AFTER STYLES.CSS

Here we will update the the HTML page to add the css style classes:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Promises Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <p>I promise to go to the gym today</p>
    <button class="resolve"">Resolve Promise</button>
    <button class="reject"">Reject Promise</button><br>
    
    <script src="scripts.js"></script>
</body>
</html>

Line 8: Here I added a <p> tag in which I added the text: “I promise to go to the gym today”, which will represent the promise made.

9-10: The class attribute is added to both buttons, the resolve styling is used on the resolve button, and the reject styling is used on the reject button.

SCRIPTS.JS

Here will will create the functionality using JavaScript:

function promiseFunc(choice) {
    return new Promise((resolve, reject) => {
        if(choice === "I will go to gym"){
            resolve("promise has been resolved")
        }
        else {
            reject("promise had been rejected")
        }
    })
}

function promiseCheck(myChoice) {
    promiseFunc(myChoice).then((msg) => {
        document.getElementById("txt").innerText = 
            "I will go to gym because " + msg

        document.getElementById("txt").style.color = "green"

    })  .catch((msg) => {
        document.getElementById("txt").innerText = 
            "I will not go to gym because " + msg

        document.getElementById("txt").style.color = "red"
    })
        
}

1-10: Is a function that is used to retrieve the choice of the user from the promiseCheck function, this function is called promiseFunc which holds the Promise class, it is returning the object of the promise for the promiseCheck to receive. In the promise’s parenthesis, we have an attribute which is arrow/anonymous function, in the function we are checking if the user has resolved the promise or rejected the promise, then using the parameters in the arrow function, resolve and reject, we use these functions to send either: “promise has been resolved” or “promise had been rejected”, respectively

12-26: Here we create the function mentioned above, promiseCheck to receive the either: “I will go to gym” if the resolve button is pressed or “I will not go to gym” if the reject button is pressed. Then call the promiseFunc function to receive the promise’s object that was returned. After that we use the .then function to receive either a resolve functions message, we then store said message in a variable named msg, we then set the inner text of a p tag with the id txt using the getElementById("txt").innerText to set the text: “I will go to gym because ” + msg, we also set the font color to green. For the .catch function which is right after the .then function, we will do the exact same thing except the text will be: “I will not go to gym because ” + msg, and the font color will be red.

INDEX.HTML AFTER SCRIPTS.JS

Now we will link the functions from scripts.js to the buttons:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Promises Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <p>I promise to go to the gym today</p>
    <button class="resolve" onclick="promiseCheck('I will go to gym')">Resolve Promise</button>
    <button class="reject" onclick="promiseCheck('I will not go to gym')">Reject Promise</button><br>
    <p id="txt"></p>
    
    <script src="scripts.js"></script>
</body>
</html>

8-9: In these lines, we will add the promiseCheck function from out JavaScript file to the buttons in the onclick attribute, so that it will be executed when clicked on. When the resolve button is pressed it will send the text: “I will go to the gym” as an argument to the promiseCheck function. We will do the same with the reject button, and we will send “I will not go to the gym”.

10: Here we will create a <p> tag, and set it an id of “txt”, so that the JavaScript can replace the text with the result.

CONCLUSION

So since read through the blog, thank you. If you don’t understand something or have question feel free to comment and we will answer it. We have covered promises in JavaScript, we gave the syntax for a promise with an example that has an explanation. If you liked the blog, please feel free to check out our other articles, the JavaScript Archives might interest you. We are also making articles on hardware as well, not just software.

Leave a Reply

Your email address will not be published. Required fields are marked *