How to use JavaScript Promise for an API call

Problem

Although there are many ways to handle asynchronous methods, sometimes we get confused about how to handle asynchronous methods in JavaScript. Reason is, different methods, which are Promise, async await, then-catch methods produce similar result.

Solution

We will see different approaches of handling asynchronous methods in JavaScript and meaning of each term. This is the first blog on async calls, in this blog we will show how to make asynchronous call using Promise API(method), in other words this blog explains how to best use Promise API to make asynchronous calls.

First thing first!

When do we use async method or why do we use async method?

Answer – When we want to make sure one call/request is complete and data (if any) from that call is received before we move to next call, in that case we create an asynchronous arrangement.

Now let’s see how to use Promise keyword for handling asynchronous method.

We will use our async project that is stored at GitHub for this.

To run the project, simply open the test.html from the project and run it in the browser.

There are 5 .js files in the project, each JavaScript file is using different way of handling the async method. To see it in action we can simply change the source of .js in the test.html file. Current file name is promise.js

Suppose our main aim is to call an API to get a students data and show all the students’ data at a place. We will be using Promise method, it takes two params, resolve and reject, it looks like this:
new Promise(resolve, reject)
Let’s understand how it works: In the value of resolve variable, we pass a method which will be called when the main method returns a value (success case) and the value returned from the main method which is the student data in this case is passed to the resolve variable (the method), now it’s the duty of the resolve method to show success message in the output. In case our main method fails which means our API failed to get the student data we will have to raise an error, so the method which will actually raise an error is received in the reject parameter of the Promise method, we may raise an error directly also like using alert box in case of error, but using the reject variable (a method) is the norm in case of Promise. Once the resolve/reject method receives its data/output, it is passed to the then method in case of success or the catch method in case of failure.  Complete code is below:
    const students = [‘Alex’, ‘Bob’]
    const validUrl = ‘https://jsonplaceholder.typicode.com/users/1’
    const incorrectUrl = ‘https://jsonplaceholder.typicode.com/users/x’
 
    function getAllstudents(student) {
        students.push(student)
        document.body.innerHTML = ‘resolve case…’
        setTimeout(() => {
            let output = ”;
            students.forEach((s, index)=> {
                output += ‘<li>’ + s + ‘</li>’ + ‘\n’
            })
            document.body.innerHTML = output
        }, 1200);
    }
 
    function errHandler(err) {
        document.write(err.toString());                   // its called when error
        console.log(err.toString())
    }
 
    function updateNewStudent(){
        var url = validUrl                                              // for resolve case
        //var url = incorrectUrl                                      // for reject case
 
        document.body.innerHTML = ‘making the API call…’
 
        return new Promise((resolve, reject)=>{
            let request = new XMLHttpRequest();
 
            request.addEventListener(“loadend”, function() {
                const response = JSON.parse(this.responseText);
                if (this.status === 200 && response.name) {
                    resolve(response.name);
                } else {
                    reject(‘some error occoured! Reject case called!’);
                }
            });
            request.open(“GET”, url, true);
            request.send();
        })
    }
 
    try{
        setTimeout(() => {
        updateNewStudent()
            .then(getAllstudents)      // this ‘getAllstudents’ is called when we resolve
            .catch(errHandler)
        }, 1200)
        document.body.innerHTML = ‘calling updateNewStudent() in 1 second…’
    }
    catch(e){
        document.write(e);
    }

When the JavaScript file gets loaded, it starts the execution from the try block,

first the updateNewStudent method is called. Inside the method we create a Promise object and inside the promise object we are making an API call.

In case of success of the API call we are passing the result in the resolve param and in case of failure we are passing the result in the reject param.

Note: The actual code inside Promise is not called until the then method is called.

Output in browser will be like as shown below :-

More from Node/Javascript:

Natalie Harris
With references from Alan Plang
132

 

Kyle Aniston
With references from Alan Plang
75

 

Kyle Aniston
With references from StackOverflow
381

 

Mike Morgan
With references from StackOverflow
105

 

Mike Morgan
Forwared by QwertyBot
560

 

Mike Morgan
Forwared by QwertyBot
1.4k

 

Kyle Aniston
Forwared by Alan Plang
1.0k

 

Kyle Aniston
Forwared by Alan Plang
1.0k

 

2 thoughts on “How to use JavaScript Promise for an API call

Leave a Reply

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