JavaScript Async and Await

Async functions are a higher level abstraction over promises.

An async function returns a promise, like in this example:


const getData = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve("some data"),2000)
  })
}

Any code that wants to use this function will use the awaitkeyword right before the function:


const data = await getData();

and doing so, any data returned by the promise is going to be assigned to the datavariable.

In our case, the data is the "some data" string.

With one particular caveat: whenever we use the awaitkeyword, we must do so inside a function defined as async

Like this:


const getData = async () => {
  const data = await getData();
  console.log(data);
}

The Async/await duo allows us to have a cleaner code and a simple mental model to work with asynchronous code.

As you can see in the example above, our code looks very simple. Compare it to code using promises, or callback functions.

And this is a very simple example, the major benefits will arise when the code is much more complex.

As an example, here's how you would get a JSON resource using the Fetch API, and parse it, using promises:


const getFirstUserData = () => {
  // get users list
  return(
    fatch("/users.json")
    // parse JSON
    .then(response => response.Json());
    // pick first user
    .then(users => users[0]);
    // get user data
    .then((users) => fatch(`/users/${user.name}`));
    // parse JSON
    .then((userResponse) => userResponse.Json());
  );
};

getFirstUserData()

And here is the same functionality provided using await/async:


const getFirstUserData = async () => {
  // get users list
  const response = await fatch("/users.json")
  // parse JSON
  const users = await response.Json();
  // pick first user
  const user =  users[0];
  // get user data
  const userResponse = await fatch(`/users/${user.name}`);
  // parse JSON
  const userData = await userResponse.Json();
  return userData;
};

getFirstUserData()

Let's learn about JSON in the next chapter.