Async/Await in JavaScript

Posted by

Async/await is a feature in JavaScript that allows you to work with asynchronous code in a more synchronous manner. This makes your code easier to read and understand. In this tutorial, we will learn how to use async/await in JavaScript.

Before we start, let’s understand what asynchronous code is. Asynchronous code allows your program to run without stopping for a task to complete. This is useful for tasks that take time to complete, like fetching data from a server.

To use async/await, you need to understand promises in JavaScript. Promises are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. Here is an example of a promise:

<!DOCTYPE html>
<html>
<head>
<title>Async/Await Tutorial</title>
</head>
<body>
<script>
function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Data fetched successfully');
    }, 2000);
  });
}

fetchData().then(data => {
  console.log(data);
});
</script>
</body>
</html>

In this example, the fetchData function returns a promise that resolves after 2 seconds. We then use the then method to handle the successful completion of the promise.

Now, let’s see how we can use async/await to make the code above more readable:

<!DOCTYPE html>
<html>
<head>
<title>Async/Await Tutorial</title>
</head>
<body>
<script>
async function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Data fetched successfully');
    }, 2000);
  });
}

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

getData();
</script>
</body>
</html>

In this example, we have replaced the then method with the await keyword inside an async function. When the getData function is called, it will wait for the fetchData function to resolve before moving on to the next line of code.

You can also use async/await with asynchronous functions that return promises. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Async/Await Tutorial</title>
</head>
<body>
<script>
function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Data fetched successfully');
    }, 2000);
  });
}

async function getData() {
  try {
    const data = await fetchData();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

getData();
</script>
</body>
</html>

In this example, we use a try/catch block to handle any errors that may occur when fetching the data. If an error occurs, it will be caught and logged to the console.

Async/await is a powerful feature in JavaScript that simplifies working with asynchronous code. It makes your code more readable and easier to understand. I hope this tutorial has helped you understand how to use async/await in JavaScript. Happy coding!

0 0 votes
Article Rating
12 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@sonatabasum1342
4 months ago

Thank you

@THE-dl8yk
4 months ago

Basically 1 and 2 print first and then Brazil because it's calling it from the Internet?

@lhisabilal
4 months ago

thank you for the knowledge

@TraceguyRune
4 months ago

Is the rain and lightning real, or were they added in post?

@berojgarengineer8099
4 months ago

Theme kon si h bro

@_acky
4 months ago

what theme is this ?

@dasa665
4 months ago

I just enjoyed the background music

@zoyafatima8435
4 months ago

you solve my problem i was stuck since 2 hours.

@chameleonnn
4 months ago

awesome 👍

@MuhammadUsman-ok5vs
4 months ago

async and await method make Asyc code sync???

@mzohaib6725
4 months ago

Brother your shorts are awesome…. You got a new subscriber.. ❤.. Thanks for such a nice and short solutions…

@appsgames3513
4 months ago

Suppose if there is some condition in JavaScript where else part is not required so will it cause any issue e.g
If ()
Console log
Else if ()
Console log
Else if ()
Console log

In above example if we not use else block so will it cause any issue