Skip to main content

JavaScript Async/Await: A Concise Guide

Async/await is a powerful feature in JavaScript that allows you to write asynchronous code in a synchronous style. Async/await makes it easier to write code that is both readable and maintainable.

In this blog post, we will explore the various features and capabilities of JavaScript async/await, including:

  • Using the async and await keywords
  • Handling resolved and rejected promises
  • Chaining asynchronous operations
  • Error handling

Using the async and await Keywords

The async keyword is used to declare an asynchronous function. An asynchronous function is a function that can be paused and resumed.

The await keyword is used to wait for a promise to resolve. When the promise resolves, the await expression will return the resolved value of the promise.

For example, the following code uses the async and await keywords to fetch data from a server:

async function fetchData() {

  const response = await fetch('https://example.com/data.json');

  const data = await response.json();


  return data;

}

The fetchData function is an asynchronous function that returns a promise. The promise will be resolved with the data from the server.


Handling Resolved and Rejected Promises

When a promise is resolved, the then method is called. The then method takes two arguments, a callback function for the resolved state and a callback function for the rejected state.

When a promise is rejected, the catch method is called. The catch method takes a callback function that is passed the error object.

For example, the following code uses the then and catch methods to handle the resolved and rejected states of the promise returned by the fetchData function:

fetchData()

  .then(data => {

    console.log(data);

  })

  .catch(error => {

    console.error(error);

  });


Chaining Asynchronous Operations

One of the most powerful features of async/await is the ability to chain asynchronous operations. Chaining asynchronous operations allows you to create a sequence of asynchronous operations that are executed one after the other.

To chain asynchronous operations, you use the await keyword to wait for the previous asynchronous operation to complete before starting the next asynchronous operation.

For example, the following code chains two asynchronous operations together to fetch data from a server and then display the data in a table:

async function displayData() {

  const data = await fetchData();


  const table = document.createElement('table');


  data.forEach(item => {

    const row = document.createElement('tr');

    const cell1 = document.createElement('td');

    const cell2 = document.createElement('td');


    cell1.textContent = item.name;

    cell2.textContent = item.age;


    row.appendChild(cell1);

    row.appendChild(cell2);


    table.appendChild(row);

  });


  document.body.appendChild(table);

}

The displayData function is an asynchronous function that returns a promise. The promise will be resolved when the data has been fetched from the server and displayed in the table.


Error Handling

Async/await provides a clean and concise way to handle errors. When a promise is rejected, the catch block is executed.

For example, the following code uses the catch block to handle errors that occur when fetching data from a server:

async function fetchData() {

  try {

    const response = await fetch('https://example.com/data.json');

    const data = await response.json();


    return data;

  } catch (error) {

    console.error(error);

  }

}

The try block contains the asynchronous code that can throw an error. The catch block contains the code that will handle the error.


Conclusion

Async/await is a powerful tool in JavaScript that allows you to write asynchronous code in a synchronous style. Async/await makes it easier to write code that is both readable and maintainable.By understanding the various features and capabilities of async/await, you can write code that is more efficient and easier to read.

Comments

Archive

Show more

Topics

Show more