Skip to content

Instantly share code, notes, and snippets.

@acidtone
Last active March 29, 2022 21:56
Show Gist options
  • Save acidtone/82944dbaa59aef9247833fe79eae3fb2 to your computer and use it in GitHub Desktop.
Save acidtone/82944dbaa59aef9247833fe79eae3fb2 to your computer and use it in GitHub Desktop.
fetch: Asynchronous JS with async/await

fetch: Asynchronous data with async/await

Problem

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.

Solution: async/await

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() using async/await

fetch() is an asynchronous function that returns a promise. We can use the async/await syntax to retrieve data by:

  1. Declaring an asynchronous function that will handle the fetch() call:

    const fetchData = async function() {
        // fetch code goes here
    }
  2. Any async function can "pause" for any function that returns a Promise by using the await keyword.

    const fetchData = async function() {
        const response = await fetch(url);
    }
  3. 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();
    }
  4. Once the JSON has been converted to data, it can be used in our script

    const fetchData = async function() {
        const response = await fetch(url);
        const data = await response.json();
        // Use the data
        console.log(data);
    }
    
    // Invoke our function
    fetchData();
  5. The above code works but it doesn't handle errors. The problem might be a 404 Not Found response.

    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();
  6. We need to check for a network error (the only time that fetch() will reject a Promise). We'll use a try...catch block for this and refactor the 404 Not Found check 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();
const fetchData = async function() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/albums');
if (!response.ok) {
throw new Error(response.statusText);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
fetchData();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment