자바스크립트 비동기 함수 (Asynchronous Functions)

In Javascript, asynchronous functions play a crucial role in executing time-consuming operations without blocking the execution of other code. They allow for non-blocking behavior, making it possible to handle tasks such as fetching data from APIs, performing file operations, or making network requests seamlessly.

What are Asynchronous Functions?

Asynchronous functions in Javascript are functions that are able to execute multiple tasks simultaneously, without waiting for each task to complete before moving on to the next one. They are typically used to handle operations that involve waiting for responses from external sources, such as API calls or database queries.

How do Asynchronous Functions work?

Javascript utilizes a mechanism called the event loop to handle asynchronous operations. When an asynchronous function is called, it is placed in the event loop, allowing the rest of the code to continue running. Once the asynchronous task is completed, a callback function is triggered, which allows the code to handle the result of the asynchronous operation.

Examples of Asynchronous Functions

1. setTimeout()

The setTimeout() function is a built-in Javascript function that delays the execution of a specified function or code block for a given amount of time. It takes two parameters: the function to be executed and the time delay in milliseconds.

setTimeout(() => {
  console.log("This message will be printed after 3 seconds");
}, 3000);

2. Promises

Promises are a more recent addition to Javascript and provide a cleaner way to handle asynchronous operations. They allow us to write code that is more readable and maintainable, by utilizing a chain of .then() and .catch() methods.

const fetchUserData = () => {
  return new Promise((resolve, reject) => {
    // Simulating an API call
    setTimeout(() => {
      const userData = { name: "John", age: 25 };
      resolve(userData);
    }, 2000);
  });
};

fetchUserData()
  .then((userData) => {
    console.log(userData);
  })
  .catch((error) => {
    console.error(error);
  });

3. Async/Await

Async/Await is a modern syntax introduced in ES2017 that allows for even cleaner and more concise code when dealing with asynchronous functions. It offers a more synchronous-looking code structure while still working asynchronously under the hood.

const fetchData = async () => {
  try {
    const response = await fetch("https://api.example.com/data");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
};

fetchData();

Conclusion

Asynchronous functions are a powerful concept in Javascript, allowing for the efficient handling of time-consuming tasks without blocking the execution of other code. Understanding how to use setTimeout(), Promises, and Async/Await can greatly enhance your ability to write efficient and scalable Javascript code.