언어/JavaScript

[async와 await] 비동기 코드를 동기처럼 쓰는 방법

Dachaes 2025. 4. 12. 01:26
728x90
반응형
728x90

async와 await 

JavaScript에서 서버 요청이나 파일 읽기처럼 시간이 걸리는 작업은 비동기(async)로 처리됩니다. 과거에는 콜백(callback)을, 그 이후엔 Promise를 사용했지만, 지금은 async/await이 비동기 처리의 표준 문법입니다.

 


1.  async/await란?

async/awaitPromise를 더 간결하고 가독성 좋게 사용하는 문법입니다. 마치 동기(synchronous) 코드처럼 작성할 수 있어서 복잡한 .then() 체인을 피할 수 있습니다.

 


2.  기본 문법

a.  async 키워드

  • 어떤 함수 앞에 async를 붙이면, 그 함수는 항상 Promise를 반환합니다.
async function greet() {
  return 'Hello!';
}

greet().then(msg => console.log(msg)); // Hello!
b.  await 키워드
  • await는 Promise가 처리될 때까지 기다림
  • async 함수 내부에서만 사용 가능
async function getData() {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  console.log(data);
}
 

3.  기존 Promise 코드 vs async/await

a.  기존 .then() 방식

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

b.  async/await 방식

async function getUser() {
  try {
    const res = await fetch('https://api.example.com/user');
    const data = await res.json();
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

getUser();
 
  • async/await는 try-catch와 함께 사용하여 에러 처리를 깔끔하게 할 수 있습니다.

 


4.  순차 처리 vs 병렬 처리

a.  순차 처리 예제

async function run() {
  const a = await wait(1000);
  const b = await wait(1000);
  console.log(a, b); // 총 2초
}
b.  병렬 처리 예제
async function run() {
  const [a, b] = await Promise.all([wait(1000), wait(1000)]);
  console.log(a, b); // 총 1초
}
  • Promise.all을 함께 사용하면 병렬로 처리하면서도 await 문법을 유지할 수 있어요.

 


5.  await 주의 사항

  • await는 반드시 Promise를 반환하는 함수 앞에만 사용하세요.
  • 일반 값을 await하면 바로 resolve됩니다.
async function test() {
  const a = await 42;       // 바로 반환됨
  const b = await Promise.resolve('ok'); // 기다림
  console.log(a, b);        // 42 'ok'
}

 


6.  예제 - 사용자 정보 가져오기

async function getUserAndPosts(userId) {
  try {
    const userRes = await fetch(`https://api.example.com/users/${userId}`);
    const user = await userRes.json();

    const postsRes = await fetch(`https://api.example.com/users/${userId}/posts`);
    const posts = await postsRes.json();

    console.log('User:', user);
    console.log('Posts:', posts);
  } catch (e) {
    console.error('에러 발생:', e);
  }
}

 


7.  async/await을 언제 사용해야 할까?

  • .then() 체인이 길고 복잡해질 때
  • 여러 개의 비동기 작업을 순차/병렬로 처리할 때
  • try-catch로 직관적인 에러 핸들링을 하고 싶을 때

 


8.  마무리

async/await는 가독성을 높이고 유지보수를 쉽게 해주는 비동기 처리의 핵심 문법입니다.

함께 보면 좋은 자료

블로그 글 :
 

반응형

 

728x90
반응형