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.
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');
}
say_hello();
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).
➡️ Remember: There are three states of promises: "pending", "fulfilled" and "rejected".
See this example.
<script> let say_hello = async() => { let result = await three_seconds(); // wait for 3 seconds. document.write(result); } let three_seconds = () => { let promise = new Promise( (resolve, reject) => { setTimeout(() => resolve( 'Hello, I am Arun Banik' ), 3000); // say hello after 3 seconds. } ); return promise; } say_hello(); </script>
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 is 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.
<body> <h2> Showing sales data (month wise) extracted from a JSON file, using async and await. </h2> <div id='sales_data'></div> </body> <script> 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 (); </script>
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.