When calling for data over the network in Javascript, the calling script won't wait for the data to come back. Instead, it continues to execute and any code that depends on the fetched data will return with an error.
ES6 added Promises which allows us to set "reminders" in our code that data is on its way.
ES7 added the async/await syntax that let's us use promises to "pause" our code for functions that are asynchronous.
fetch() is an asynchronous function that returns a promise. We can use the async/await syntax to retrieve data by:
-
Declaring an asynchronous function that will handle the
fetch()call:const fetchData = async function() { // fetch code goes here }
-
Any
asyncfunction can "pause" for any function that returns a Promise by using theawaitkeyword.const fetchData = async function() { const response = await fetch(url); }
-
This response most often contains JSON data, which needs to be converted to a Javascript value (usually an array or object). Since this data could be quite large, we also perform this operation asynchronously using
response.json(), which returns a Promise:const fetchData = async function() { const response = await fetch(url); // Convert JSON to Javascript object/array const data = await response.json(); }
-
Once the JSON has been converted to
data, it can be used in our scriptconst fetchData = async function() { const response = await fetch(url); const data = await response.json(); // Use the data console.log(data); } // Invoke our function fetchData();
-
The above code works but it doesn't handle errors. The problem might be a
404 Not Foundresponse.const fetchData = async function() { const response = await fetch('not-a-real-url'); // Check for 404 or other problem if (!response.ok) { console.error(response.statusText); } const data = await response.json(); console.log(data); } fetchData();
-
We need to check for a network error (the only time that
fetch()will reject a Promise). We'll use atry...catchblock for this and refactor the404 Not Foundcheck to throw an error.const fetchData = async function() { try { const response = await fetch('not-a-real-url'); if (!response.ok) { // Throw error to catch() throw new Error(response.statusText); } const data = await response.json(); console.log(data); } catch (error) { // Handle any rejected Promise in the `try` block console.log(error); } } fetchData();