Handling Asynchronous Operations in Javascript
Tags: javascript, codenewbie
Published: 2020-07-05 22:40:10

Asynchronous operations are a very vital aspect of Javascript and they give us the ability to make HTTP requests from a database in order to display data to our web pages. 


For a very long time, Asynchronous Javascript and XML(AJAX) using the XMLHttpRequest (XHR)  was the gold standard for handling these operations however with the introduction of the Fetch API in conjunction with the Async/await syntax, we now have a simpler way of making these requests.


In this article, we are going to be retrieving random data about a user from the random user API which offers a bunch of randomly generated information about a user, including their title, first and last names, Email etc.


Let's assume we have two files in our current directory, an `index.html` and a `script.js` file. We will be styling our CSS directly in the HTML file.


```javascript
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ASYNCHRONOUS JAVASCRIPT</title>
    <style>
        .userInfo {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100vh;
            padding: 40px
        }

        .text {
            text-align: center;
        }

         h3, p {
            text-align: center;
        }
    </style>
</head>
<body>
    <div class = "userInfo">
        <h3>Handling Asynchrous operations in Javascript</h3>
        <p> We are getting some random user's data using Fetch Requests/Async-await syntax and displaying the data.</p><br>
        <img id = "myImg">
        <div class = 'text'>
            <p id = "title"></p>
            <p id = "first"></p>
            <div id = "text">Last Name: </div>
            <p id = "mail"></p>
            <p id = "city"></p>
            <p id = "state"></p>
            <p id = "country"></p> 
        </div> 
    </div>
    <script src = "script.js"></script>
</body>
</html>
```


Take a close look at the structure of our HTML page and observe the information we are going to be retrieving from the API which we will display within the `<p>` tags which we have given an ID with the corresponding names and an image of the user.


Now let's write some javascript code. First we select all the DOM elements we need in order to display the information.


```javascript
const myImg = document.getElementById("myImg")
const title = document.getElementById("title")
const first = document.getElementById("first")
const text = document.getElementById("text")
const mail = document.getElementById("mail")
const city = document.getElementById("city")
const state = document.getElementById("state")
const country = document.getElementById("country")
```


 Next, we define a function, which I'll name `getUser` within which we will make the fetch request which will return a promise. As such, we are going to use the `.then` syntax. Later we will refactor the code to use the much newer Async/await which is basically syntactic sugar for our code.

```javascript
const getUser = () => { 
   fetch("https://randomuser.me/api") 
   .then(res => res.json())    
   .then(data => 
   console.log(data.results[0]))   
}
```


To use the fetch API, we first type the word `fetch()`. This takes an argument which is the URL of the API we are trying to make a request to and in this instance is `"https://randomuser.me/api"`. This request returns a promise which we will handle with the `.then` syntax. Next, we convert it to a JSON object. This returns another promise, which we handle again, and this time we get the data.


Now let's refactor the code to use the newer Async await syntax
```javascript
const getUser = async() => { 
   const userInfo = await fetch("https://randomuser.me/api")
   const data = await userInfo.json()  
}
```


Here we pass the keyword `async` just before our parameter and the `await` the fetch request. We assign the value obtained to the variable `userInfo`. Afterward, we convert this to JSON format and also store this in a variable which we name `data`.


Now we have access to the information we need.
Here is a screenshot of what our API returns in JSON format

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/gjjvcedkp2mk7km6vuiy.png)

Notice how our information is stored in a JSON object as an array called `results` with a single object. First, let's get the image:

```javascript
   const getUser = async() => {
    const userInfo = await fetch("https://randomuser.me/api")
    const data = await userInfo.json()
    const image = data.results[0].picture.large;
    myImg.src = image;
}

getUser()

```
To get the image, we type `data.results[0].picture.large` which returns a URL, we then assign it as the source file(src) to the image `<img>` tag we earlier picked from our DOM elements. This displays the image in our browser.


Next, we pick the titles and the names. This is also straightforward.

```javascript
    title.innerHTML = data.results[0].name.title;
    first.innerHTML = data.results[0].name.first;

```

Now go back to the HTML and notice how we do not have a `<p> `tag for the last name in the file structure. Instead, we have a `<div>` with an ID of "text". This is because we are going to generate it dynamically within the javascript using the `document.createElement()` method.

```javascript
     const lastName = document.createElement('p');

```

Next, we create a TextNode, which is basically the content we want our `<p>` tag we just created to have:

```javascript
     const last_name = data.results[0].name.last     
     const textnode = document.createTextNode(last_name)
```


We will then append our textNode to our `<p>` tag
```javascript
     let surName = lastName.appendChild(textNode)
```

Lastly we will append it to our `<div>`

```
text.appendChild(surName)

```
Finally we get the remaining information

```javascript
    mail.innerHTML = data.results[0].email
    city.innerHTML = data.results[0].location.city
    state.innerHTML = data.results[0].location.state
    country.innerHTML = data.results[0].location.country
```
Let's join all our code together:


```javascript

const getUser = async() => {
    const userInfo= await fetch("https://randomuser.me/api")
    const data = await userInfo.json()

    const image = data.results[0].picture.large;
    myImg.src = image;

    title.innerHTML = `Title: ${data.results[0].name.title}`;

    first.innerHTML = `First-Name : ${data.results[0].name.first}`;

   const last_name = data.results[0].name.last

   const lastName = document.createElement('p');

   const textNode = document.createTextNode(last_name)

   let surName = lastName.appendChild(textNode)
    
   text.appendChild(surName)

   mail.innerHTML = `Email Address : ${data.results[0].email}`
    
   city.innerHTML = `City: ${data.results[0].location.city}`

  state.innerHTML = `State : ${data.results[0].location.state}`
   
country.innerHTML = `Country: ${data.results[0].location.country}`

 // Fetch API
 //   .then(res => res.json())
 //    .then(data => console.log(data.results[0].name.first))
}

getUser()

```


Here is what our final Output would look like:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/53x57i8p0nwaw5uw2oe3.png)


You can get the code on this link:

https://github.com/yahayakenny/asynchronous_javascript_operations