A Meeting With Asynchronous Javascript, Promises and Fetch Requests.

spoiler - it is a confrontation.

A Meeting With Asynchronous Javascript, Promises and Fetch Requests.

Hello again, friend of a friend, i knew you when- . Sorry i couldn't resist. I really just meant to type 'Hello again'. That intro was from a movie, Scott Pilgrim vs The World and it is pretty cool.

Back to the purpose of this blog post.

So, I had this interview and I was asked about some of the code wrote in something I built. It's a covid-19 tracker built with Vue and you can find it here.

I made a fetch request to an API and i was asked to explain it. The fetch request looked like this

async fetchCovidData() {
      const res = await fetch('https://api.covid19api.com/summary')
      const data = await res.json()
      return data
    }

A fetch request allows you to request data from a resource. Now I know what a fetch request does, I knew it basically gets my data, and technically I'm right but there's more to it.

I was then asked to explain what await and async mean and I thought I knew and I sort of explained how I understood it but there were things missing.

The interview went alright but i was sort of mortified. I mean, look at me, messing up in an interview. My interviewer was really cool and he explained it to me and it was great.

So i decided to go and learn more about these things and that is why we are here today.

Writing about this sort of makes sense since my last blog post was about API's and you can read it here.

Side note : I am aware this is a blog post but I wonder if I am being too informal with my language.

Anyways,

ASYNCHRONOUS JAVASCRIPT, WHAT ARE YOU?

Yes, like I said, this is a confrontation.

So there's Asynchronous and Synchronous code and i shall explain.

Synchronous Code

  • Very unproblematic and chill.
  • Executes by starting from the top of the file till it gets to the bottom of the file.

Asynchronous Code

  • Problematic and so not chill.

  • Asynchronous code starts off the same and may run into a function or some code then split off and execute that block of code separately from the rest of the code. Usually because it needs to wait (await) and do some operations (fetch).

I'll give some examples.

// Synchronous code

let a = 1
let b = 2

console.log('amala is trash')
console.log(a)
console.log(b)

// results on the console 
// amala is trash
//  1
//  2

// executes top to bottom
// asynchronous code

let a = 1
let b = 2

setTimeout(function(){
   console.log('amala is trash')
 }, 2000)
console.log(a)
console.log(b)

// results on the console
// 1
// 2
// amala is trash

This code did not follow the regular pattern of top to bottom because the setTimeout doesnt run the function until after 2000 milliseconds, and at that point, all the other code would have run.

This shows the difference between the two and also the fact that i never miss an opportunity to diss amala.

There are other built in forms of asynchronous code in Javascript and that brings us to Promises

What is a Promise?

By definition,

A promise is a declaration or assurance that one will do something or that a particular thing will happen

and

A Javascript promise object represents the eventual completion (or failure) of an asynchronous operation and it's resulting value

Look at Javascript being more reliable than....nevermind.

Javascript promises usually have a .then or a .catch coming after a function. For example,

fetch('/overrated').then(function() {
    console.log('superman')
})

Basically, Javascript is promising me that when it completes the fetch from the overrated directory, it's going to log 'superman' to the console.

A Promise in Javascript is like a regular promise. 'I promise to watch all 10 seasons of Friends' and like any other promise just like the most probable outcome of this one, it can be broken/failed/rejected or if God intervenes, it can be kept/completed/resolved.

For more about promises, you can check this really cool article here

Now back to my meeting with asynchronous javascript, promises and fetch requests, how do they fit?

Bringing this back

async fetchCovidData() {
      const res = await fetch('https://api.covid19api.com/summary')
      const data = await res.json()
      return data
    }

This is basically just an asynchronous function with a promise.

Using 'async', 'await' is just a way of making promises easier.

To use this, you need to have a function where your awaiting code is in

hence

async fetchCovidData() {

 }

'fetchCovidData' is the name of my function. The 'async' just tells Javascript that it is an asynchronous function and it can mind its business.

const res = await fetch('https://api.covid19api.com/summary')

'await' tells the code to wait until the fetch request is executed and then it will do the next thing. It will return the resolved section of the promise and store it in 'res' aka the response.

const data = await res.json
return data

This does the same thing and its basically just extracting the JSON data from the response object and storing it in data. It then returns data so i can use it in the rest of my code.

To learn more about fetch requests, check here .

That brings us to the end of this post. I wish i could've explained it like this in my interview sha.

Thank you for reading this. Enjoy this video.

CONNECT WITH ME