Blog
WK Hui life

async and await are keywords used in asynchronous programming in languages like JavaScript, C#, and Python. They are used to simplify the process of writing code that involves asynchronous operations, such as fetching data from a server, reading files, or performing time-consuming tasks. Here’s the difference between async and await:

  1. async:
  • The async keyword is used to define a function as asynchronous. An asynchronous function returns a promise implicitly, indicating that it will execute asynchronously and might not complete immediately.
  • An async function can contain one or more await expressions, which pause the execution of the function until the awaited promise is resolved.
  1. await:
  • The await keyword is used within an async function to pause its execution until a promise is resolved. It can only be used inside an async function.
  • When an await expression is encountered, the event loop is allowed to continue processing other tasks, making the program more responsive and efficient.

Here’s a simple example in JavaScript to illustrate the usage of async and await:

// Using async and await to fetch data from an API

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 fetching data:', error);
  }
}

// Calling the async function
fetchData().then(data => {
  console.log('Fetched data:', data);
});

In this example, the fetchData function is defined as async, which allows the use of the await keyword within it. The await keyword is used to pause the execution of the function until the fetch promise is resolved, and then the response is processed using another await for parsing the JSON data.

In summary, async is used to define a function as asynchronous, while await is used within an async function to pause its execution until a promise is resolved. This combination makes asynchronous programming in languages like JavaScript more readable and easier to manage, especially when dealing with complex chains of asynchronous operations.