Asynchronicity in javascript
Using keywords like "async" and "await" might be a scary task to someone new to programming, so let's take a dive and explore how it works!
If you are completely new to asynchronous requests, then no worries, I will give a quick explanation. In JavaScript, much like the real world, you have tasks that finish instantly, like turning on the lights. Also, some tasks have a delay, like talking to someone which would be seen as asynchronous. Javascript handles both of these requests differently. If you haven't worked with APIs or time-sensitive requests, you have probably been coding like this
let lightsStatus = false
function displayLightsStatus(){
console.log(lightsStatus)
}
But when we are talking to a web interface that requires time to receive data, we have to wait, because if we request data before the data is received, we are going to have a big problem!
Say we make a request to a joke API to get a dad joke. There is going to be time between when we send the request, and when we get the joke back, so we are going to have to wait before accessing the data. Let's take a look at what that would look like without waiting, and with waiting. I'm using the Axios request library for this example, and the website "https://icanhazdadjoke.com/" to provide me with dad jokes.
//incorrect way to wait for a response(no waiting at all)
import axios from "axios"
let url = "https://icanhazdadjoke.com/"
function getjoke(){
let request = axios.get(url,{
headers: {
Accept: "application/json", // Set the Accept header to specify JSON response
},
})
console.log(request.data.joke) //alteratively request['data']['joke']
}
getjoke()
Now we expect this to return a dad joke but nope, we didn't wait at all and we wanted the results before the request was completed. This is the error that I received.
TypeError: Cannot read properties of undefined (reading 'joke')
at getjoke (file:///Users/dannerbaumgartner/webproject/main.js:10:30)
We got this error because javascript is trying to access data that is not available yet, and it's telling us that you can't access the data because it is undefined, which means that the data is nonexistent.
Now if we want to fix this we are going to have to use two keywords, which are "async" and "await". The keyword "async" lets JavaScript know that the function we are declaring is asynchronous and we are going to need to wait for it to finish before we go searching for the data within it. The "await" keyword tells JavaScript to pause execution until the data is received. This is the correct way to make an asynchronous request.
//correct way to wait for a response
import axios from "axios"
let url = "https://icanhazdadjoke.com/"
async function getjoke(){
let request = await axios.get(url,{
headers: {
Accept: "application/json", // Set the Accept header to specify JSON response
},
})
console.log(request.data.joke) //alteratively request['data']['joke']
}
getjoke()
Now we get a dad joke printed in our Node.js terminal. Here is what the output looks like.
dannerbaumgartner@Danners-MacBook-Air webproject % node main.js
Why is it a bad idea to iron your four-leaf clover? Cause you shouldn't press your luck.
Awesome! Now you can laugh at some dad jokes, or make something cool with your new knowledge about how async works in javascript! You can try this dad joke request in this codepen
