Understanding JavaScript Async Await

Hey - Nick here! This page is a free excerpt from my $99 course JavaScript Fundamentals.

If you want the full course, click here to sign up and create an account.

I have a 30-day satisfaction guarantee, so there's no risk (and a ton of upside!) in signing up for this course and leveling up your JavaScript developer skills today!

In this tutorial, you will learn about JavaScript async await, which is a new syntax that allows you to use the async and await keywords for a much nicer way to work with promises in JavaScript.

Table of Contents

You can skip to a specific section of this JavaScript async await tutorial using the table of contents below:

How to Use the JavaScript async and await Keywords

The first thing you need to know about the JavaScript async and await keywords is that your function that creates your promises stays exactly the same.

As a quick reminder, here is our promise generating function from our last lesson:


function makePie(pieType){

    const piePromise = new Promise(function(resolve, reject){

        resolve(`Your ${pieType} pie is ready!`);

        reject(`Something went wrong with your ${pieType} pie!`)

    });

    return piePromise;

}

To see this in action (and get more practice!) let’s actually build a new promise generating function from scratch. We will call the function promiseBuilder, and it will accept an argument called milliseconds that specifies how long the function should wait before resolving the promise.


function promiseBuilder(milliseconds = 0){

	return new Promise ((resolve) => {

		setTimeout(resolve, milliseconds);

}

}

Now let’s see how we can use the async and await keywords to reference promiseBuilder in a separate function, but wait until the promise is resolved before proceeding further through that function.

First, let’s build the function that references promiseBuilder. We will call this function consoleLogger, and it’s purpose will be to log the statements Before promiseBuilder and After promiseBuilder to the console.

Here’s what this looks like:


function consoleLogger(){

    console.log('Before promiseBuilder');

    console.log('After promiseBuilder');

}

Now let’s add a reference to promiseBuilder between each of the console.log statements. Specifically, let’s pass in a milliseconds argument of 2000, which is equivalent to 2 seconds:


function consoleLogger(){

    console.log('Before promiseBuilder');

    promiseBuilder(2000);

    console.log('Before promiseBuilder');

}

We saw in the last tutorial that this won’t actually wait two seconds before logging both statements to the console. To fix this, we can either follow the convoluted methods from the last lesson, or we can use the much easier async and await keywords.

Let’s explore how we could force the consoleLogger function to wait until the promise is resolved before proceeding past its call to the promiseBuilder function.

The first thing that we need to do is transform the consoleLogger function into an async function. This is very simple. All you need to do is add the async keyword in front of the function keyword, like this:


async function consoleLogger(){

    console.log('Before promiseBuilder');

    promiseBuilder(2000);

    console.log('Before promiseBuilder');

}

Next, you need to add the await keyword in front of the call to the promiseBuilder function, like this:


async function consoleLogger(){

    console.log('Before promiseBuilder');

    await promiseBuilder(2000);

    console.log('Before promiseBuilder');

}

This method is vastly superior to the corresponding strategies we discussed in the last lesson from a readability perspective. Because of this, developers almost exclusively use the async await method for dealing when JavaScript promises today.

Using JavaScript async await With Different Types of JavaScript Functions

As we saw earlier in this course, there are a number of different ways that you can write functions in JavaScript.

The async await keywords can be used in each of these types of functions. We will explore them one-by-one in this section of this tutorial.

Using JavaScript async await With Arrows Functions

To use the JavaScript async await keywords with arrow functions, you must place the async keyword before the function’s arguments and the await keyword inside of the function block.

Here is an example:


const consoleLogger = async () {await promiseBuilder(2000)}

Using JavaScript async await With Callback Functions

Recall that callback functions are functions that are generated inside of an addEventListener method, and are invoked in response to that JavaScript event.

Here is an example of how you could use the async await keywords with a callback function in JavaScript:


button = document.querySelector('button');

button.addEventListeners('click', async function (){

    await promiseBuilder(2000);

    console.log('You clicked the button!');

})

Using JavaScript async await With Object Methods

We have seen that object methods are nothing but functions that live inside of JavaScript objects and can be called on those objects using the dot operator.

Here is how you could use JavaScript async await inside of a JavaScript object method:


const me = {

    name: 'Nick',

    age: 24,

    moeny: 0,

    sellCourse: async function(amount)){

        this.money += amount;

        await promiseBuilder(2000);

    }

}

Final Thoughts

In this tutorial, you learned about the async and await keywords in JavaScript.

Here is a brief summary of what we discussed in this lesson:

  • How your promise generating function does not need to be modified when using the async and await keywords
  • How to use JavaScript async await to wait until a promise is resolved before proceeding through a function
  • How to use JavaScript async await in different types of functions, including arrow functions, callback functions, and object methods

JavaScript async await is a fairly sophisticated topic that can be difficult to understand. Because of this, I have made sure to include plenty of practice problems in the next section.