DEV Community

Aditya Singh
Aditya Singh

Posted on

Understanding async/await in JavaScript

💡 async/await is built on top of Promises and provides a more readable way to write asynchronous code. The async keyword is used to define a function that returns a Promise. Inside an async function, you can use the await keyword before an expression that returns a Promise.

Asynchronous Function:

// Simulating an asynchronous operation with a Promise
function fetchUserData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const user = { id: 1, name: 'John Doe' };
      resolve(user);
    }, 1000);
  });
}

// Using async/await to handle the Promise
async function getUserData() {
  try {
    const user = await fetchUserData();
    console.log('User:', user);
    return user;
  } catch (error) {
    console.error('Error fetching user data:', error);
    throw error;
  }
}
Enter fullscreen mode Exit fullscreen mode

In this example, getUserData() is an async function that uses the await keyword before calling fetchUserData(). When getUserData() is called, it waits for the fetchUserData() Promise to resolve before logging the user data to the console.

Error Handling:

function performTask() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const success = Math.random() < 0.5; // Simulating success/failure
      if (success) {
        resolve('Task completed successfully!');
      } else {
        reject(new Error('Task failed.'));
      }
    }, 1500);
  });
}

async function doTask() {
  try {
    const result = await performTask();
    console.log(result);
  } catch (error) {
    console.error('Error:', error.message);
  }
}

Enter fullscreen mode Exit fullscreen mode

In this example, doTask() awaits the result of performTask() and handles both success and failure scenarios using the try-catch block.

Multiple Async Operations:

Async/await makes it easier to deal with multiple asynchronous operations. You can use await with multiple Promises, and they will execute sequentially.

function fetchResource(url) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(`Resource loaded from ${url}`);
    }, 800);
  });
}

async function loadResources() {
  const resource1 = await fetchResource('https://example.com/resource1');
  console.log(resource1);

  const resource2 = await fetchResource('https://example.com/resource2');
  console.log(resource2);

  const resource3 = await fetchResource('https://example.com/resource3');
  console.log(resource3);
}

loadResources();
Enter fullscreen mode Exit fullscreen mode

In this example, loadResources() loads three resources sequentially using await, ensuring each operation completes before moving on to the next.

Conclusion:

With async/await, managing Promises and handling errors become more intuitive and less error-prone. As you move deeper into JavaScript development, mastering async/await will prove to be an essential skill for building efficient and responsive applications.

Top comments (0)