2.4 Await and Async Keywords

2.4 Await and Async Keywords

Async and Await are relatively new concepts in JavaScript (Introduced in 2017). The main goal of these keywords was to remove the “callback pyramid of doom”:
Here’s how you use async:
async function myFunction() { return "Hello"; }
By putting “async” before “function” we are automatically telling “myFunction” to return a Promise.
So, it’s the same thing as:
async function myFunction() { return Promise.resolve("Hello"); }
Here’s how you use await:
async function fetchMovies() { const res = await fetch(‘/movies’); return await res.json(); }
Here, “await” is telling the computer to try to complete the Promise. The “await” keyword pauses execution until the Promise is fulfilled, resolved, or rejected. Pausing execution is helpful when the subsequent lines of synchronous code requires the result of the Promise you’re waiting for to complete.
The results of this task (whether fulfilled or failed) will be in the “res” variable. This variable tells you what has happened and what’s returned after your promise resolves.
You might have noticed that the await keyword makes our program behave synchronously. In the above example, the program stops at the res assignment statement until the Promise returned by fetch is fulfilled (or rejected). When this finally happens, the fetchMovies() only returns after the Promise returned by res.json() fulfills.
When possible, you want to process Promises simultaneously, instead of line by line. For example, your code might structurally resemble the following:
//This async timeout used to simulate actual async operations function asyncTimeout(duration) { return new Promise((resolve, reject) => { setTimeout( function() => { resolve(“Done!”); }, duration); }); } async asyncSimulation() { //begin processing all the promises together let promise1 = asyncTimeout(2000); let promise2 = asyncTimeout(2000); let promise3 = asyncTimeout(2000); //Pausing execution to wait for all promises to fulfill await promise1; await promise2; await promise3; }
Here, the timeout Promises are meant to simulate asynchronous operations (you’ll of course have your own promises when writing your programs). AsyncSimulation() synchronously starts processing all the promises. Then, “await” to pause execution until all the promises are fulfilled. That way, we won’t have to wait for each promise one by one.


HTTP Request

In this problem, you’ll learn to make an HTTP Request with fetch(). Fetch receives one parameter - the URL or object you want to fetch, then returns the promise. Write the necessary code to complete the request and display the data from the response on the console (you need not parse or use the data, but that would be great).
Note: If you request the URL of a random webpage you find, you will likely get an “access to fetch blocked by CORS policy” error. For security reasons, Webpages cannot allow just anyone to request their data - so the CORS policy blocks unauthorized requests for most URLs of published webpages.

Previous Section

2.3 Promises
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.