Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Write an Asynchronous Function with async/await

    Marius SchulzMarius Schulz

    This lesson introduces the ES2017 async and await keywords. It shows how to write a short asynchronous function that makes an HTTP request and parses the response.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Here, we have a short function that talks to the GitHub API. It loads a specific user. Once the response comes back, it parses the body as JSON.

    Finally, the user's name and location are logged to the console. Let's run this program to make sure it works. Yes, everything seems to work just fine.

    Let's now see how we can convert the function into an asynchronous function using the async and await keywords. First, we're going to make the function asynchronous by adding the async keyword. Next, we're going to use the await operator to wait until the fetch call completes.

    The await operator takes a promise and then pauses the function execution until that promise is settled. It then does one of two things. If the promise is rejected, the await expression throws the rejected value.

    If the promise is resolved, the await expression will return the resolved value. We can then take it and assign it to a variable like this.

    The next thing we want to do is take the body of the response and parse it as JSON. We'll say, "Const user equals await response at JSON."

    The JSON method returns a promise as well. This means we can use the await operator again to wait until that promise is settled. Now that we have the user, let's go ahead and log their name to the console.

    Let's also log their location just like we did before.

    Finally, let's run the program one more time to make sure we haven't broken anything. As we can see, everything still works. Let's take a look at our asynchronous function one more time. The body of the function almost reads like sequential synchronous code.

    We can read one statement at a time from top to bottom. We no longer have any indentation or then methods in a promise chain. Oftentimes, this makes it a lot easier to understand the control flow within an asynchronous function.