DEV Community

Cover image for Exploring the Magic of async/await in JavaScript!
Ajisafe Oluwapelumi
Ajisafe Oluwapelumi

Posted on

Exploring the Magic of async/await in JavaScript!

Today, we're going to uncover async and await. In JavaScript, there are some tasks that can take some time, like asking for information from the internet or reading special files. Instead of making the whole computer wait for these tasks to finish, JavaScript allows other tasks to be handled at the same time while it waits for the response from time-taking tasks. Sometimes, we want to wait for the response before starting other tasks, and that's where async and await comes in.

async

In simple words, async is a special word we put in front of a function to tell our computer, "Hey, inside this function, there might be things that take a bit of time to finish."

async function getData() {
  // Asynchronous operation
}
Enter fullscreen mode Exit fullscreen mode

await

We use the await keyword inside an async function and it's a way to tell our computer, "Hey, take a break and pause execution here until this thing is done."

async function main() {
  const result = await getData(); // Pauses until getData() is resolved
  console.log(result);
}
Enter fullscreen mode Exit fullscreen mode

Let's explore the use of async and await with some examples.

Example 1: Without async/await

// Imagine fetching a cat fact from an API using Promises

function main() {
  const url = 'https://catfact.ninja/fact';
  const response = fetch(url);
  console.log(response.fact); // Oops! This won't work as expected
  console.log('Cat Fact Ninja!');
}

function fetch(url) {
  return new Promise((resolve, reject) => {
    // Fetch the cat fact from the API
  });
}

main();
Enter fullscreen mode Exit fullscreen mode

In this example, we have two functions: main() and fetch(url).

The fetch(url) function takes a URL as input and returns a Promise (a Promise ensures that our request is completed). Inside this Promise, we request a cat fact from the internet.

The main() function starts by setting a URL for a cat fact API. Then it calls the fetch(url) function to get the cat fact data. Since fetch(url) returns data from the internet, it doesn't immediately provide the result, the function takes time. Therefore, when we try to log response.fact, it won't work correctly. The next console.log() statement and 'Cat Fact Ninja!' will be printed before the fetch(url) is resolved and this is not what we want. We can fix this in the next example.

Example 2: With async/await

// Now let's fetch a cat fact using async/await

async function main() {
  const url = 'https://catfact.ninja/fact';
  const response = await fetch(url); // We await the promise to finish
  console.log(response.fact); // This works perfectly now!
  console.log('Cat Fact Ninja!');
}

function fetch(url) {
  return new Promise((resolve, reject) => {
    // Fetch the cat fact from the API
  });
}

main();
Enter fullscreen mode Exit fullscreen mode

In this example, we've made a slight change by using the async keyword in the main() function.

The main() function is now marked as async, which means we can use the await keyword inside it. When await is used before calling fetch(url), it pauses the execution of the main() function until we get the result we want. This way, the cat fact data is fetched and assigned to the response variable before moving on. Now, when we log response.fact, it will correctly show the cat fact fetched from the API because we were waiting for the function to return using await.

async and await help us do cool things with our code, even if those things take time. If you've got thoughts or stories about using them, I'd love to hear them. Drop a comment below and share your experiences, your feedback means a lot!

Top comments (0)