Async/Await in JavaScript simplied in 3 minutes

Hi, I’m just going take a few minutes to simplify how async and await works in JavaScript.

Image for post
Image for post

So, it’s basically a line of code waiting for the data returned by a JavaScript’s promise to be fully resolved or rejected before moving onto the next line of code.

Let me give you a brief example on how to start using async/await as this is currently the best practice.

We should always consider these things before making use of async await.

  • The code that is ought to run, should be inside a function.
  • Example of a regular javascript function using async await

function async asyncExample() {}

  • Example of an ES6 function using async await (notice where the ‘async’ is)

asyncExample = async () => {}

  • The function should contain try and catch method to properly handle errors and successful codes within the function as the case may be.
  • The line of code that should be waited for, should be added await including a variable name. Giving it a variable name helps the next of code manipulate the data gotten from the awaited code which was either resolved or rejected.

AsyncExample = async () => {

try{

Let getData = await fetch (’http://json.data’)

Let dataReturned = getData.json()

console.log(dataReturned)

}

catch(error){

console.log(error)

return error

}

}

Now, the asynchronous code above, returns & console’s the data gotten from the API in a json format.

So, the variable getData runs first, followed by dataReturned (variable) but as the case may be the variable dataReturned waits for the variable getData to run (returning all promises, which equally means all the data the URL contains) before converting/parsing the gotten data into a JSON format.

However, some data returned from URLs or requests made are in a text format (though this is generally not recommended) and this would make the obtained data throw the following error if we tried converting it into a JSON format.

SyntaxError: Unexpected token E in JSON at position 0

This actually means that the data gotten from the API was not a json object, possibly the API returned a text (which is not json, this could be a simple statement or word).

We need to change the code from

- Let dataReturned = getData.json();

To

- Let dataReturned = getData.text();

This would help the data appropriately return the result/data without any errors.

So, we’ve come to the end of this amazing session. 😃

FullStack Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store