DEV Community

Cover image for Async/Await in Javascript
Valentina Peric
Valentina Peric

Posted on

1

Async/Await in Javascript

Reading codebases and seeing async/await in functions may look a little tricky. With this article, you will see how they work and notice that it is a clever, easier way to work with asynchronous functions.

Prerequisites đź“ť

  1. A working knowledge of promises (I will give a quick refresher, if you do not remember!)
  2. A working knowledge of try/catch
  3. A code editor (I recommend Visual Studio Code)

Let's Get Started ✨

First, let's breakdown the async keyword

When you see the async keyword before a function, this means that the function is going to return a promise. (here's the refresher!!!) A promise, in simple terms, is an object that contains the results of the eventual completion or failure of an asynchronous operation. Let's see it in action,

async function brewCoffee() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("coffee is done! enjoy :)"), 2000)
  });

  try {
    let coffee = await promise;
    console.log(coffee);
  } catch(error) {
    console.log('error', error);
  }
}

brewCoffee();

//output: coffee is done! enjoy :)
Enter fullscreen mode Exit fullscreen mode

The function brewCoffee starts with a promise that will resolve after 2 seconds. That promise will be assigned to the variable coffee which will be printed out. If the promise is rejected, the error will be printed out in the catch.

How does await play a role?

The await keyword will pause the execution of the function so the promise can resolve.

How they both work together

The await keyword is declared in the async function. Often, you will see async/await in API calls. This will make sure the data is correctly fetched before other lines of code are called. For example,

async function fetchCappiccunoRecipe() {
  const response = await fetch('https://api.sampleapis.com/coffee/hot');
  const recipe = await response.json();
  return recipe; 
}

function makeCoffee(recipe) {
  console.log('The coffee was made with this ', recipe);
}

async function barista() {
  const recipe = await fetchCappiccunoRecipe();
  makeCoffee(recipe); 
}

barista();
Enter fullscreen mode Exit fullscreen mode

When the barista function is called, the recipe will be fetched which will be passed in as a parameter in the makeCoffee function.

Key Takeaways ✨

async/await will make your code easier to work with, especially since it makes it more readable. It is also a more concise way of writing asynchronous functions. Alternatively, it could have been written like this,

function fetchCappiccunoRecipe() {
  return fetch('https://api.sampleapis.com/coffee/hot');
}

function makeCoffee(recipe) {
  console.log('The coffee was made with this ', recipe);
}

function barista() {
  fetchCappiccunoRecipe().then((response) => {
    response.json().then((recipe) => {
      makeCoffee(recipe); 
    });
  });
}

barista();
Enter fullscreen mode Exit fullscreen mode

You can see that there is more nesting and callback functions. Overall, a more confusing experience.

Next Steps ✨

There may be opportunities in your code base to refactor functions to use async/await. I recommend this article on migrating promises into async/await functions: https://afteracademy.com/blog/migrating-from-promise-chains-to-async-await/ if you need additional guidance! Thanks for reading and happy coding :)

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

đź‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay