Using async and await to Read data from an external JSON file

← PrevNext →

You can use Ajax in JavaScript to read data from an external JSON file. Here in this, post I’ll show you how to read and extract data from an external JSON file in JavaScript using async and await.

This method is much cleaner and thinner than other methods that I have used to extract data from remote files. It is easy to understand and implement.


async/await example in JavaScript

Let us understand async and await first.

The async Function

An async function is declared with the keyword async. For example,

let say_hello = async() => {
  document.write('Hello, I am Arun');

Its simple.

You can read and understand more about async function here.

The await Operator

The await operator is used within a function that has the async keyword. The operator works only inside async functions.

await makes a script wait or pause till a promise is fulfilled (or settled) or rejected. It can reject a promise (Now, that HURTs).

See this example.

let say_hello = async() => {
  let result = await three_seconds();   // wait for 3 seconds.

let three_seconds = () => {
  let promise = new Promise(
    (resolve, reject) => {
      setTimeout(() => resolve( 
        'Hello, I am Arun Banik'
      ), 3000);			// say hello after 3 seconds.
  return promise;

Try it

Note: You cannot use await without async. Remove async keyword from the above function and it will throw an error like this …

Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules

This entire operation is done asynchronously using this combo, async and await.

It was just an intro. In-fact there is more to it. Now, let’s get on with the JSON example.

Read JSON file using async and await.

We’ll now use the async and await keywords in our JavaScript code to extract data from a remote JSON file.

    Showing sales data (month wise) extracted from a JSON file, using async and await.
  <div id='sales_data'></div>

    let figures = '';
    let get_sales_data = async() => {
      let url = " ../../library/sample-sales.json";
      let response = await fetch (url);
      const arrSales = await response.json();
      let result = arrSales.reduce((prev, cur) =>
            figures = figures + '<span>' + cur.Month + '</span> ' +
		    '<span>' + cur.Sales_Figure + '</span> <br />', '');
      document.getElementById('sales_data').innerHTML = result;

    get_sales_data ();
Try it

👉 Now you can convert JSON data fetched from a file using async and await to an HTML table

Let me explain. Its an async function, therefore, I have used the await operator. It fetches the data from the JSON file named sample-sales.json. I had to provide the complete url or the location of the file.

It waits until the data is fetched and then it stores the JSON in an array. Using the reduce() method, I am extracting data from the array and displays it.

That's it. Thanks for reading.

← PreviousNext →