티스토리 뷰

부트캠프/Front

[JavaScript] async / await란?

혀니hyun 2025. 3. 18. 10:13

 

 

JavaScript에서 비동기 코드를 더 간결하고 직관적으로 작성할 수 있도록 도와주는 ES8(ES2017) 기능.

 

기존의 Promise 기반 코드를 async / await을 사용하면 동기 코드처럼 읽히는 비동기 코드로 변환할 수 있다.

 


1. 기본 사용법

 

async 함수

async 키워드를 함수 앞에 붙이면, 항상 Promise를 반환하는 함수가 됨.

async function hello() {
    return "안녕!";
}

hello().then(console.log); // "안녕!" (Promise가 반환되므로 `.then()` 사용 가능)

 

✅ await 키워드

await 키워드는 Promise가 처리될 때까지 기다린 후 그 결과를 반환.

(단, await async 함수 내부에서만 사용 가능)

async function getMessage() {
    let message = await hello();
    console.log(message); // "안녕!"
}

getMessage();

 

 


2. async/await vs Promise.then()

 

☁️ Promise.then() 방식 (콜백 중첩 문제)

function fetchData() {
    return new Promise((resolve) => {
        setTimeout(() => resolve("데이터 받아옴!"), 2000);
    });
}

fetchData().then((data) => {
    console.log(data); // "데이터 받아옴!" (2초 후 출력)
});

 

🌟 async/await 방식 (더 직관적인 코드)

async function getData() {
    let data = await fetchData();
    console.log(data); // "데이터 받아옴!" (2초 후 출력)
}

getData();

 async/await을 사용하면 코드가 더 깔끔하고 가독성이 좋아짐.

 


3. try...catch로 에러 핸들링

 

await을 사용할 때는 반드시 에러 처리를 고려해야 함.

기본적으로 try...catch 블록을 사용해서 에러 처리.

async function fetchWithError() {
    try {
        let response = await fetch("https://invalid-url.com");
        let data = await response.json();
        console.log(data);
    } catch (error) {
        console.error("에러 발생!", error);
    }
}

fetchWithError(); // "에러 발생!" (잘못된 URL이므로 에러 발생)

 

 


4. Promise.all()과 async/await

 

비동기 작업을 병렬로 실행하고 싶다면 Promise.all() async/await을 함께 사용.

async function fetchMultiple() {
    let [data1, data2] = await Promise.all([
        fetch("https://jsonplaceholder.typicode.com/posts/1").then(res => res.json()),
        fetch("https://jsonplaceholder.typicode.com/posts/2").then(res => res.json())
    ]);

    console.log(data1, data2);
}

fetchMultiple();

Promise.all()을 사용하면 여러 요청을 동시에 실행하므로 더 빠르게 데이터를 가져올 수 있음.

 


5. async/await 정리

 

 async 함수는 항상 Promise를 반환함.

 await 비동기 작업이 끝날 때까지 기다린 후 결과를 반환함.

 try...catch를 사용하여 에러를 처리해야 함.

 Promise.all()과 함께 사용하면 비동기 작업을 병렬 실행 가능.

 

async/await은 비동기 코드를 더 읽기 쉽고, 동기 코드처럼 작성할 수 있도록 도와줌

'부트캠프 > Front' 카테고리의 다른 글

[JavaScript] 디자인 패턴  (0) 2025.03.19
[JavaScript, HTML, CSS] Spread Sheet 앱 만들기  (0) 2025.03.18
[JavaScript] Promise란?  (0) 2025.03.18
[JavaScript] fetch, try, catch란?  (0) 2025.03.18
[JavaScript] class vs 생성자 함수  (0) 2025.03.18
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG more
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함