Front-end/JavaScript

JS) then vs async/await ... (예시: fetch API)

오열매 2023. 3. 1. 11:00

fetch API에서 async/await과 then은 모두 비동기 코드를 작성하는 방법입니다. 각각의 사용 시기는 코드 구조 및 개발자 선호도에 따라 다를 수 있습니다.

 

async/await를 사용한 비동기 작업

async/await는 비동기 코드를 작성할 때 사용됩니다. fetch API는 네트워크 요청이 비동기적으로 처리되기 때문에, async/await를 사용하여 코드를 동기적으로 작성할 수 있습니다.

 

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

fetchData();

 

then을 사용한 비동기 작업

then을 사용하여 비동기 작업을 처리할 수도 있습니다. 이를 통해 콜백 지옥(callback hell)과 같은 비동기 코드의 복잡성을 감소시킬 수 있습니다.

 

fetch('https://example.com/data.json')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

 

선택은 개발자의 코드 구조와 개발 스타일에 따라

then과 async/await은 모두 비동기 코드를 작성하는 방법으로, 선택은 개발자가 코드 구조와 개발 스타일에 따라 다를 수 있습니다. 그러나 보통은 async/await을 더 선호하는 경향이 있습니다.

 

 

결론

개발자는 코드 구조와 개발 스타일에 따라 선택할 수 있으며, 이를 통해 비동기 작업을 보다 효율적으로 처리할 수 있습니다.