The async function is the code we use to define an asynchronous function. The async function returns a Promise as its result. Async functions run in an order that’s separate from other code in the event loop. An async function does not need to contain an await expression.
An await expression causes an async function to pause until the passed promise has resolved before executing the rest of the code in a function. While the async function pauses, any calling function will continue to run. Await expressions only work inside an async.
Example 1 demonstrates that we can only use the await expression inside an async function. Any attempts to use the await expression outside of an async function will throw an exception.
Example 2 demonstrates how to correct the error generated in Example 1. To fix the error, we need to change the standard function goToSleep into an async function. You can see by looking at the code in Example 2 that the only necessary change is to add the word async before the word function in our goToSleep function declaration.
We can now see that in this example, the async function goToSleep first uses console.log to alert the user that we are going to bed now. Next, we tell the function goToSleep to await while we call the standard non-async function sleep, and wait for it to finish. Once the sleep function ends, goToSleep starts back up and uses consol.log again to alert the user that we finished sleeping.
If you break down the code, you can see it’s pretty straightforward.
1. The console uses its warning expression console.warn to let us know that it’s about to fetch some json.
a. Console.warn is the same as console.log but with a highlighted background to show importance.
b. The warning lets us know that it might take some time to fetch the data. So this code is functioning almost like a loading screen.
2. With the warning issued, we call the async function getData and pass it the dataURL https://www.mocky.io/v2/5de9064331000023ac6b166d
a. The first await expression pauses the function and waits for a response from the website to let us know we established a connection.
b. Once connected, the second await expression pauses the function again until it can download the contents into the myJson constant.
3. With the async function getData finished, we use the consoles warning statement again to let the user know that the code is finished loading and is ready to present the json.
4. We use another console statement, console.dir, to present the json to the user.
a. Console.dir is similar to console.log, but is for printing objects and properties instead of strings.