Dseok의 실전 예제로 웹개발 한방에 끝내기

웹개발, 혼자 하려니 막막하고 힘드시죠? 저 또한 그렇습니다. 힘든 웹개발... 실전 예제를 통해 함께 공부해요!!!!😁📕

Javascript

[Dseok의 코딩스터디] JavaScript async/await 한방에 끝내기 | 개념 & 실전 예제 10가지

Dseok 2025. 3. 6. 14:12
반응형
SMALL

📌 async/await란?

JavaScript의 async/await비동기 코드의 가독성을 향상시키고, 복잡한 콜백(callback) 또는 .then() 체인을 간결하게 관리할 수 있도록 도와주는 기능입니다.

✅ 기본 문법

async function fetchData() {
  return "데이터를 가져왔습니다!";
}

fetchData().then(console.log); // "데이터를 가져왔습니다!"
  • async 키워드를 함수 앞에 붙이면 해당 함수는 항상 Promise를 반환
  • await 키워드를 사용하면 Promise가 해결될 때까지 기다린 후, 결과 값을 반환
async function fetchData() {
  const result = await Promise.resolve("데이터를 가져왔습니다!");
  console.log(result); // "데이터를 가져왔습니다!"
}
fetchData();
 

📌 async/await의 주요 활용 사례

  1. 비동기 데이터 호출 (API 요청)
  2. 순차적인 비동기 작업 처리
  3. 병렬 처리 (Promise.all)
  4. 타이머 기반 비동기 처리
  5. 파일 읽기 및 쓰기 (Node.js)
  6. 비동기 루프 (for-await-of)
  7. WebSocket과의 통신
  8. 블록체인 트랜잭션 처리
  9. 대규모 데이터 처리
  10. AI 모델의 비동기 API 호출

 

📌 async/await 실전 예제 10가지

1️⃣ API 호출 (fetch)

async function getUser() {
  const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
  const data = await response.json();
  console.log(data);
}
getUser();

설명: fetch()await로 감싸 비동기 요청을 간결하게 처리함.

 

2️⃣ 여러 개의 API 호출 순차 실행

async function fetchSequentialData() {
  const user = await fetch("https://jsonplaceholder.typicode.com/users/1").then(res => res.json());
  console.log("사용자 데이터:", user);

  const posts = await fetch("https://jsonplaceholder.typicode.com/posts?userId=1").then(res => res.json());
  console.log("사용자의 게시물:", posts);
}
fetchSequentialData();

설명: 첫 번째 API 호출이 완료된 후 두 번째 API 호출을 수행.

 

3️⃣ Promise.all을 활용한 병렬 처리

async function fetchParallelData() {
  const [user, posts] = await Promise.all([
    fetch("https://jsonplaceholder.typicode.com/users/1").then(res => res.json()),
    fetch("https://jsonplaceholder.typicode.com/posts?userId=1").then(res => res.json())
  ]);
  console.log("사용자:", user);
  console.log("게시물:", posts);
}
fetchParallelData();

설명: Promise.all을 사용하여 여러 개의 비동기 요청을 동시에 처리.

 

4️⃣ 타이머 기반 비동기 처리 (setTimeout)

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function waitAndPrint() {
  console.log("3초 후 메시지 출력 중...");
  await delay(3000);
  console.log("3초가 지났습니다!");
}
waitAndPrint();

설명: await를 사용하여 setTimeout()과 같은 비동기 동작을 더 쉽게 제어 가능.

 

5️⃣ 파일 읽기 및 쓰기 (Node.js)

const fs = require("fs").promises;

async function readFileAsync() {
  try {
    const data = await fs.readFile("example.txt", "utf8");
    console.log(data);
  } catch (error) {
    console.error("파일을 읽는 중 오류 발생:", error);
  }
}
readFileAsync();

설명: Node.js 환경에서 파일을 비동기적으로 읽고 처리할 때 사용.

 

6️⃣ 비동기 루프 (for-await-of)

async function fetchMultipleURLs(urls) {
  for await (const url of urls.map(fetch)) {
    const data = await url.json();
    console.log(data);
  }
}
fetchMultipleURLs([
  "https://jsonplaceholder.typicode.com/users/1",
  "https://jsonplaceholder.typicode.com/users/2"
]);

설명: 여러 개의 API 호출을 for-await-of를 활용하여 효율적으로 처리 가능.

 

7️⃣ WebSocket과의 통신

const socket = new WebSocket("wss://example.com/socket");

socket.onmessage = async (event) => {
  const message = await JSON.parse(event.data);
  console.log("수신된 메시지:", message);
};

설명: WebSocket을 통해 실시간으로 데이터를 수신하고 처리.

 

8️⃣ 블록체인 트랜잭션 처리

async function checkTransactionStatus(txHash) {
  const response = await fetch(`https://blockchain-api.com/tx/${txHash}`);
  const data = await response.json();
  console.log("트랜잭션 상태:", data.status);
}
checkTransactionStatus("0x123456789...");

설명: 블록체인 네트워크에서 트랜잭션 상태를 비동기적으로 조회 가능.

 

9️⃣ 대규모 데이터 처리

async function processLargeData() {
  const largeArray = new Array(100000).fill(0).map((_, i) => i);
  for await (const chunk of largeArray) {
    console.log("처리 중:", chunk);
  }
}
processLargeData();

설명: 대량의 데이터를 for-await-of을 활용하여 성능 저하 없이 처리 가능.

 

🔟 AI 모델의 비동기 API 호출

async function getAIResponse(input) {
  const response = await fetch("https://ai-api.com/analyze", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ query: input })
  });
  const result = await response.json();
  console.log("AI 응답:", result);
}
getAIResponse("이 문장을 분석해주세요.");

설명: AI API를 호출하여 텍스트 분석을 수행할 때 사용 가능.

📌 마무리 🎯

🔑 async/await 핵심 정리

  • 비동기 코드를 동기적인 방식처럼 작성 가능
  • 콜백 지옥(callback hell) 해결
  • 비동기 작업을 순차 또는 병렬로 실행 가능 (Promise.all)
  • 이벤트 루프와 태스크 큐를 이용하여 효율적인 실행 흐름 유지
  • 메모리 최적화를 고려하여 비동기 코드 작성 필요

반응형
LIST