#atom
Content:
The async and await keywords in JavaScript provide a modern and syntactically cleaner way to work with asynchronous code. They are built on top of Promises and allow you to write asynchronous code that looks and behaves like synchronous code, making it easier to read and maintain.

Key Concepts:

  1. async Functions:

    • An async function is a function declared with the async keyword.
    • It automatically returns a Promise. If the function returns a value, the Promise is resolved with that value. If the function throws an error, the Promise is rejected.
    • Example:
      async function fetchData() {
        return "Data fetched!";
      }
      
      fetchData().then((result) => console.log(result)); // "Data fetched!"
      
  2. await Keyword:

    • The await keyword can only be used inside an async function.
    • It pauses the execution of the async function until the Promise it is waiting for is resolved or rejected.
    • If the Promise is resolved, await returns the resolved value. If the Promise is rejected, it throws an error, which can be caught using try/catch.
    • Example:
      async function fetchData() {
        const response = await fetch("https://api.example.com/data");
        const data = await response.json();
        return data;
      }
      
  3. Error Handling:

    • Errors in async functions can be handled using try/catch blocks, similar to synchronous code.
    • Example:
      async function fetchData() {
        try {
          const response = await fetch("https://api.example.com/data");
          if (!response.ok) {
            throw new Error("Network response was not ok");
          }
          const data = await response.json();
          return data;
        } catch (error) {
          console.error("Error fetching data:", error);
        }
      }
      
  4. Sequential vs Concurrent Execution:

    • await can be used to run asynchronous operations sequentially or concurrently.
    • Sequential Execution:
      async function sequential() {
        const result1 = await fetchData1();
        const result2 = await fetchData2();
        return [result1, result2];
      }
      
    • Concurrent Execution:
      async function concurrent() {
        const promise1 = fetchData1();
        const promise2 = fetchData2();
        const [result1, result2] = await Promise.all([promise1, promise2]);
        return [result1, result2];
      }
      
  5. Top-Level await:

    • In modern JavaScript environments (e.g., ES modules), await can be used at the top level of a module without needing an async function.
    • Example:
      const data = await fetchData();
      console.log(data);
      

Example: Fetching Data with async/await

async function fetchUserData(userId) {
  try {
    const response = await fetch(`https://api.example.com/users/${userId}`);
    if (!response.ok) {
      throw new Error("User not found");
    }
    const userData = await response.json();
    return userData;
  } catch (error) {
    console.error("Error fetching user data:", error);
  }
}

fetchUserData(1).then((user) => console.log(user));

Example: Combining async/await with Promises

async function processData() {
  const data = await fetchData();
  const processedData = await process(data);
  return saveData(processedData);
}

processData()
  .then(() => console.log("Data processed and saved!"))
  .catch((error) => console.error("Error:", error));

Benefits of async/await:

Linked Cards:

Tags: #JavaScript #AsyncAwait #AsynchronousProgramming #Promises #ErrorHandling #ControlFlow

Connections:


Sources: