Blog

async await Example | JavaScript

Key Takeaways

  • async/await offers a cleaner syntax for handling promises in JavaScript.
  • The async keyword defines an asynchronous function that returns a Promise.
  • Use try..catch with async/await to handle errors effectively.
  • Arrow functions can also be used with async/await.
const asyncActivity = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(1), 5000);
  });
};

async function myFunction() {
  try {
    const result = await asyncActivity();
    console.log("Result is: " + result);
  } catch (error) {
    console.error("Error: ", error);
  }
}

myFunction();

The async and await keywords are syntactic sugar for Promises in JavaScript. They allow for writing asynchronous code in a more synchronous-looking style, making it easier to read and maintain.

The equivalent function using then() would look like this:

function myFunction() {
  asyncActivity()
    .then(result => console.log("Result is: " + result))
    .catch(error => console.error("Error: ", error));
}

myFunction();

When you prepend the async keyword to a function, it enables the use of await inside it to pause execution until the promise settles.

Using Promise Chains with async/await

For complex asynchronous workflows, async/await significantly cleans up the syntax compared to traditional promise chaining, enhancing code readability:

// Promise chaining using traditional then()
function myFunction() {
  async1()
    .then(result1 => async2(result1))
    .then(result2 => async3(result2))
    .then(result3 => console.log("Final result: ", result3))
    .catch(error => console.error("Error in chain: ", error));
}

// Promise chaining using async/await
async function myFunction() {
  try {
    const result1 = await async1();
    const result2 = await async2(result1);
    const result3 = await async3(result2);
    console.log("Final result: ", result3);
  } catch (error) {
    console.error("Error in async function: ", error);
  }
}

async await vs promises

Although async/await doesn't introduce new functionality compared to Promises, it simplifies the coding style, making error handling more straightforward and the codebase easier to follow.

async await arrow function

ES6 allows you to create async functions using arrow syntax as well:

const myFunction = async () => {
  try {
    const result = await asyncActivity();
    console.log("Result is: " + result);
  } catch (error) {
    console.error("Error: ", error);
  }
};

myFunction();

async await try catch

Error handling in async/await functions is clean and intuitive with a standard try..catch block. This approach helps manage asynchronous errors like synchronous code:

async function errorProneFunction() {
  try {
    const result = await asyncActivity();
    console.log(result);
    throw new Error("Intentional error"); // Example of triggering an error
  } catch (error) {
    console.error("Caught an error: ", error.message);
  }
}

errorProneFunction();

FAQ

What are the main benefits of using async/await over Promises?

Async/await offers a more readable and maintainable code structure for handling asynchronous operations. It reduces the amount of nested code and makes error handling simpler.

Can you use async/await for all Promise-based functions?

Yes, any function that returns a Promise can be used with async/await. It simplifies the syntax but the underlying behavior remains unchanged.

What happens if you don’t use try..catch with async/await?

If you don't handle errors explicitly with try..catch, unhandled promise rejections will occur, potentially causing issues in your code. It's best practice to handle errors to ensure robustness.

How do async/await functions impact performance?

Using async/await itself doesn't incur performance penalties. However, proper error handling and asynchronous design remain crucial for optimal application performance.

Mastering the tech interviewWhat everyone is doing wrong in tech interviews