DEV Community

Ankush Goyal
Ankush Goyal

Posted on

Javascript: async/await

async and await are powerful features in JavaScript that make working with Promises easier and more readable. They allow you to write asynchronous code that looks and behaves like synchronous code. Here's a quick overview:

async Function

  • Definition: An async function is a function that returns a Promise. It allows you to use await within it.
  • Syntax:
  async function myFunction() {
    // Your code here
  }
Enter fullscreen mode Exit fullscreen mode

await Keyword

  • Definition: The await keyword can only be used inside an async function. It pauses the execution of the async function and waits for the Promise to resolve or reject.
  • Syntax:
  let result = await somePromise;
Enter fullscreen mode Exit fullscreen mode

Example

Here's a simple example to demonstrate how async and await work together:

function fetchData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('Data fetched');
    }, 2000);
  });
}

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

getData();
Enter fullscreen mode Exit fullscreen mode

In this example:

  1. fetchData is a function that returns a Promise, which resolves after 2 seconds.
  2. getData is an async function that uses await to wait for fetchData to resolve.
  3. When getData is called, it logs "Fetching data...", waits for fetchData to resolve, and then logs "Data fetched".

Benefits

  • Readability: async/await makes asynchronous code look more like synchronous code, which can be easier to read and understand.
  • Error Handling: You can use try...catch blocks with async/await to handle errors more cleanly.

Error Handling Example

async function getData() {
  try {
    console.log('Fetching data...');
    const data = await fetchData();
    console.log(data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

getData();
Enter fullscreen mode Exit fullscreen mode

In this example, if fetchData were to reject, the error would be caught by the catch block, and "Error fetching data:" would be logged along with the error message.


Thank you for reading!
I hope you found this article helpful and informative. If you enjoyed it or learned something new, feel free to share your thoughts in the comments or connect with me.

If you'd like to support my work and help me create more content like this, consider buying me a coffee. Your support means the world and keeps me motivated!

Thanks again for stopping by! 😊

Buy Me A Coffee

Top comments (0)