Sobes.tech
Middle

Why is the async keyword needed before a function? What does it do?

sobes.tech AI

Answer from AI

The keyword async before a function indicates that this function is asynchronous and always returns a promise.

What it does:

  • Allows the use of the await operator inside the function to wait for the result of promises, making asynchronous code more readable and similar to synchronous code.
  • If the function returns a value, it is automatically wrapped in a promise that resolves with that value.
  • If an error occurs inside the function, it causes the returned promise to be rejected.

Example:

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error:', error);
  }
}

fetchData().then(data => console.log(data));

Thus, async simplifies working with asynchronous code, making it more understandable and easier to read.

Why is the async keyword needed before a function… - sobes.tech