JavaScript 비동기 패턴 마스터하기: 콜백에서 Async/Await까지

Patricia Arquette
풀어 주다: 2024-09-13 20:16:39
원래의
390명이 탐색했습니다.

Mastering JavaScript Async Patterns: From Callbacks to Async/Await

비동기 JavaScript를 처음 접했을 때 콜백 때문에 어려움을 겪었고 Promise가 내부적으로 어떻게 작동하는지 전혀 몰랐습니다. 시간이 지나면서 Promise와 async/await에 대해 배우면서 코딩에 대한 접근 방식이 바뀌어 훨씬 더 관리하기 쉬워졌습니다. 이 블로그에서는 이러한 비동기 패턴을 단계별로 살펴보고 개발 프로세스를 간소화하고 코드를 더 깔끔하고 효율적으로 만드는 방법을 공개합니다. 이러한 개념을 함께 살펴보고 알아봅시다!

비동기 JavaScript를 배워야 하는 이유는 무엇입니까?

비동기 JavaScript를 배우는 것은 현대 웹 개발에 필수적입니다. 이를 통해 API 요청과 같은 작업을 효율적으로 처리하고 애플리케이션의 응답성과 속도를 빠르게 유지할 수 있습니다. Promise 및 async/await와 같은 비동기 기술을 익히는 것은 확장 가능한 애플리케이션을 구축하는 것뿐만 아니라 이러한 개념을 이해하는 것이 주요 초점인 JavaScript 취업 면접에서 성공하는 데에도 중요합니다. 비동기 JavaScript를 마스터하면 코딩 기술을 향상하고 실제 과제에 더 잘 대비할 수 있습니다.

비동기 패턴이란 무엇입니까?

JavaScript의 비동기 패턴은 애플리케이션을 정지하지 않고 서버에서 데이터를 가져오는 등 시간이 걸리는 작업을 처리하는 데 사용되는 기술입니다. 처음에 개발자는 콜백을 사용하여 이러한 작업을 관리했지만 이 접근 방식으로 인해 "콜백 지옥"이라고 알려진 복잡하고 읽기 어려운 코드가 생성되는 경우가 많았습니다. 이를 단순화하기 위해 Promise가 도입되어 작업을 연결하고 오류를 보다 우아하게 처리함으로써 비동기 작업을 처리하는 더 깔끔한 방법을 제공했습니다. async/await로 진화가 계속되었습니다. 이를 통해 동기 코드처럼 보이고 동작하는 비동기 코드를 작성할 수 있어 읽기 및 유지 관리가 더 쉬워졌습니다. 이러한 패턴은 효율적이고 반응이 빠른 애플리케이션을 구축하는 데 중요하며 최신 JavaScript 개발의 기본입니다. 이 블로그 전체에서 이러한 개념을 더 자세히 살펴보겠습니다.

콜백이 뭐야?

콜백은 수신 함수가 특정 시점에 콜백을 실행할 목적으로 다른 함수에 인수로 전달하는 함수입니다. 이는 서버에서 데이터를 가져오거나 계산을 마친 후와 같이 특정 작업이 완료된 후 일부 코드가 실행되도록 하려는 시나리오에 유용합니다.

콜백 작동 방식:

  1. 함수(콜백)를 정의합니다.
  2. 이 함수를 다른 함수의 인수로 전달합니다.
  3. 수신 함수는 적절한 시간에 콜백을 실행합니다.

예시 1

function fetchData(callback) {
  // Simulate fetching data with a delay
  setTimeout(() => {
    const data = "Data fetched";
    callback(data); // Call the callback function with the fetched data
  }, 1000);
}

function processData(data) {
  console.log("Processing:", data);
}

fetchData(processData); // fetchData will call processData with the data

로그인 후 복사

예 2

// Function that adds two numbers and uses a callback to return the result
function addNumbers(a, b, callback) {
  const result = a + b;
  callback(result); // Call the callback function with the result
}

// Callback function to handle the result
function displayResult(result) {
  console.log("The result is:", result);
}

// Call addNumbers with the displayResult callback
addNumbers(5, 3, displayResult);

로그인 후 복사

참고: 콜백은 비동기 작업을 처리하는 데 효과적이라고 생각하지만 주의하세요. 특히 중첩된 콜백의 경우 코드가 복잡해지면 콜백 지옥이라는 문제가 발생할 수 있습니다. 이 문제는 콜백이 서로 깊게 중첩되어 가독성 문제를 일으키고 코드를 유지 관리하기 어렵게 만들 때 발생합니다.

콜백 지옥

콜백 지옥(Pyramid of Doom이라고도 함)은 중첩된 콜백이 여러 개 있는 상황을 말합니다. 이는 여러 비동기 작업을 순차적으로 수행해야 하고 각 작업이 이전 작업에 의존하는 경우에 발생합니다.

예. 이는 읽고 유지하기 어려운 "피라미드" 구조를 만듭니다.

fetchData(function(data1) {
  processData1(data1, function(result1) {
    processData2(result1, function(result2) {
      processData3(result2, function(result3) {
        console.log("Final result:", result3);
      });
    });
  });
});

로그인 후 복사

콜백 지옥 문제:

  1. 가독성: 코드를 읽고 이해하기 어려워집니다.
  2. 유지관리성: 변경이나 디버깅이 어려워집니다.
  3. 오류 처리: 오류 관리가 복잡해질 수 있습니다.

콜백으로 오류 처리하기

콜백 작업 시 오류 우선 콜백이라는 패턴을 사용하는 것이 일반적입니다. 이 패턴에서 콜백 함수는 첫 번째 인수로 오류를 사용합니다. 오류가 없으면 첫 번째 인수는 일반적으로 null이거나 정의되지 않으며 실제 결과는 두 번째 인수로 제공됩니다.

function fetchData(callback) {
  setTimeout(() => {
    const error = null; // Or `new Error("Some error occurred")` if there's an error
    const data = "Data fetched";
    callback(error, data); // Pass error and data to the callback
  }, 1000);
}

function processData(error, data) {
  if (error) {
    console.error("Error:", error);
    return;
  }
  console.log("Processing:", data);
}

fetchData(processData); // `processData` will handle both error and data

로그인 후 복사

참고: 콜백 이후 JavaScript에서 비동기 프로세스를 처리하기 위해 Promise가 도입되었습니다. 이제 Promise에 대해 더 자세히 알아보고 내부적으로 어떻게 작동하는지 살펴보겠습니다.

약속 소개

Promise는 비동기 작업의 최종 완료(또는 실패)와 결과 값을 나타내는 객체입니다. 콜백에 비해 비동기 코드를 처리하는 더 깔끔한 방법을 제공합니다.

약속의 목적:

  1. Avoid Callback Hell: Promises help manage multiple asynchronous operations without deep nesting.
  2. Improve Readability: Promises provide a more readable way to handle sequences of asynchronous tasks.

Promise States

A Promise can be in one of three states:

  1. Pending: The initial state, before the promise has been resolved or rejected.
  2. Fulfilled: The state when the operation completes successfully, and resolve has been called.
  3. Rejected: The state when the operation fails, and reject has been called.

Note: If you want to explore more, you should check out Understand How Promises Work Under the Hood where I discuss how promises work under the hood.

example 1

// Creating a new promise
const myPromise = new Promise((resolve, reject) => {
  const success = true; // Simulate success or failure
  if (success) {
    resolve("Operation successful!"); // If successful, call resolve
  } else {
    reject("Operation failed!"); // If failed, call reject
  }
});

// Using the promise
myPromise
  .then((message) => {
    console.log(message); // Handle the successful case
  })
  .catch((error) => {
    console.error(error); // Handle the error case
  });

로그인 후 복사

example 2

const examplePromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    const success = Math.random() > 0.5; // Randomly succeed or fail
    if (success) {
      resolve("Success!");
    } else {
      reject("Failure.");
    }
  }, 1000);
});

console.log("Promise state: Pending...");

// To check the state, you would use `.then()` or `.catch()`
examplePromise
  .then((message) => {
    console.log("Promise state: Fulfilled");
    console.log(message);
  })
  .catch((error) => {
    console.log("Promise state: Rejected");
    console.error(error);
  });

로그인 후 복사

Chaining Promises

Chaining allows you to perform multiple asynchronous operations in sequence, with each step depending on the result of the previous one.

Chaining promises is a powerful feature of JavaScript that allows you to perform a sequence of asynchronous operations where each step depends on the result of the previous one. This approach is much cleaner and more readable compared to deeply nested callbacks.

How Promise Chaining Works

Promise chaining involves connecting multiple promises in a sequence. Each promise in the chain executes only after the previous promise is resolved, and the result of each promise can be passed to the next step in the chain.

function step1() {
  return new Promise((resolve) => {
    setTimeout(() => resolve("Step 1 completed"), 1000);
  });
}

function step2(message) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(message + " -> Step 2 completed"), 1000);
  });
}

function step3(message) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(message + " -> Step 3 completed"), 1000);
  });
}

// Chaining the promises
step1()
  .then(result => step2(result))
  .then(result => step3(result))
  .then(finalResult => console.log(finalResult))
  .catch(error => console.error("Error:", error));

로그인 후 복사

Disadvantages of Chaining:
While chaining promises improves readability compared to nested callbacks, it can still become unwieldy if the chain becomes too long or complex. This can lead to readability issues similar to those seen with callback hell.

Note: To address these challenges, async and await were introduced to provide an even more readable and straightforward way to handle asynchronous operations in JavaScript.

Introduction to Async/Await

async and await are keywords introduced in JavaScript to make handling asynchronous code more readable and easier to work with.

  • async: Marks a function as asynchronous. An async function always returns a promise, and it allows the use of await within it.
  • await: Pauses the execution of the async function until the promise resolves, making it easier to work with asynchronous results in a synchronous-like fashion.
async function fetchData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("Data fetched");
    }, 1000);
  });
}

async function getData() {
  const data = await fetchData(); // Wait for fetchData to resolve
  console.log(data); // Logs "Data fetched"
}

getData();

로그인 후 복사

How Async/Await Works

1. Async Functions Always Return a Promise:

No matter what you return from an async function, it will always be wrapped in a promise. For example:

async function example() {
  return "Hello";
}

example().then(console.log); // Logs "Hello"

로그인 후 복사

Even though example() returns a string, it is automatically wrapped in a promise.

2. Await Pauses Execution:

The await keyword pauses the execution of an async function until the promise it is waiting for resolves.

async function example() {
  console.log("Start");
  const result = await new Promise((resolve) => {
    setTimeout(() => {
      resolve("Done");
    }, 1000);
  });
  console.log(result); // Logs "Done" after 1 second
}

example();

로그인 후 복사

In this example:

  • "Start" is logged immediately.
  • The await pauses execution until the promise resolves after 1 second.
  • "Done" is logged after the promise resolves.

Error Handling with Async/Await

Handling errors with async/await is done using try/catch blocks, which makes error handling more intuitive compared to promise chains.

async function fetchData() {
  throw new Error("Something went wrong!");
}

async function getData() {
  try {
    const data = await fetchData();
    console.log(data);
  } catch (error) {
    console.error("Error:", error.message); // Logs "Error: Something went wrong!"
  }
}

getData();

로그인 후 복사

With Promises, you handle errors using .catch():

fetchData()
  .then(data => console.log(data))
  .catch(error => console.error("Error:", error.message));

로그인 후 복사

Using async/await with try/catch often results in cleaner and more readable code.

Combining Async/Await with Promises

You can use async/await with existing promise-based functions seamlessly.

example

function fetchData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("Data fetched");
    }, 1000);
  });
}

async function getData() {
  const data = await fetchData(); // Wait for the promise to resolve
  console.log(data); // Logs "Data fetched"
}

getData();

로그인 후 복사

Best Practices:

  1. Utilisez async/await pour plus de lisibilité : Lorsqu'il s'agit de plusieurs opérations asynchrones, async/await peut rendre le code plus linéaire et plus facile à comprendre.
  2. Combiner avec des promesses : Continuez à utiliser async/await avec des fonctions basées sur des promesses pour gérer plus naturellement les flux asynchrones complexes.
  3. Gestion des erreurs : Utilisez toujours des blocs try/catch dans les fonctions asynchrones pour gérer les erreurs potentielles.

Conclusion

async et wait offrent un moyen plus propre et plus lisible de gérer les opérations asynchrones par rapport au chaînage de promesses et aux rappels traditionnels. En vous permettant d'écrire du code asynchrone qui ressemble et se comporte comme du code synchrone, ils simplifient la logique complexe et améliorent la gestion des erreurs avec les blocs try/catch. L'utilisation de async/await avec des promesses permet d'obtenir un code plus maintenable et plus compréhensible.

위 내용은 JavaScript 비동기 패턴 마스터하기: 콜백에서 Async/Await까지의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!