🥬Aysnc/Await

An asynchronous operation (async) is a process that takes some time to complete, and does not block the execution of code while it is running. This allows your program to perform other tasks while the asynchronous operation is being carried out.

There are several ways to perform asynchronous operations in JavaScript. One common way is to use async/await.

Here is an example of an asynchronous operation using async/await:

async function getData() {
  // This is an asynchronous operation
  const response = await fetch('https://example.com/data');
  const data = await response.json();

  // This line of code will not run until the data has been retrieved
  console.log(data);
}

// This function call is asynchronous
getData();

console.log('This line of code will run before the data has been retrieved');

In this example, the getData function performs an asynchronous operation by using the fetch function to retrieve data from a remote server. The await keyword is used to wait for the data to be retrieved before the rest of the function is executed.

While the getData function is waiting for the data to be retrieved, the rest of the code continues to run. This is why the console.log statement outside of the getData function is executed before the data has been retrieved.

Async/await makes it easier to write asynchronous code that is easy to read and understand. It allows you to use familiar control structures like if and for when working with asynchronous operations, rather than having to use complex callback functions.

Last updated