DEV Community

Chandru
Chandru

Posted on

JavaScript `async` and `await`

When working with APIs or other asynchronous operations in JavaScript, you'll often use async and await.

They make asynchronous code easier to read and understand.

async

The async keyword makes a function return a Promise.

async function getMessage() {
  return "Hello World";
}
Enter fullscreen mode Exit fullscreen mode

Because it's an async function, the result is a Promise.

await

await waits for a Promise to finish before continuing.

async function getData() {
  const response = await fetch("https://api.example.com/users");
  const data = await response.json();

  console.log(data);
}
Enter fullscreen mode Exit fullscreen mode

Instead of writing:

fetch(url)
  .then(response => response.json())
  .then(data => console.log(data));
Enter fullscreen mode Exit fullscreen mode

we can use async/await, which is usually easier to read.

Error handling

Use try...catch to handle errors:

async function getData() {
  try {
    const response = await fetch(url);
    const data = await response.json();

    console.log(data);
  } catch (error) {
    console.error(error);
  }
}
Enter fullscreen mode Exit fullscreen mode

Simple rule to remember

async → makes a function return a Promise
await → waits for a Promise
try/catch → handles errors
Enter fullscreen mode Exit fullscreen mode

That's the basic idea behind async and await in JavaScript.

Top comments (0)