Async와 Await, 비동기 코드를 깔끔하게!

정원·2023년 3월 28일

JS

목록 보기
2/2

2032.03.28 홍팍(유튜브) JS async-await

기존에 콜백지옥을 체이닝기법(프로미스)를 이용해 개선했다.

비동기 코드를 조금 더 직관적으로 위해 나온 방법이 async-await이다.

1. async 란

  • 비동기 처리를 위한 문법
  • 특정 함수가 Promise를 반환하게 함
  • 기존 프로미스보다 더 간결한, 직관적인 코드 작성가능
  • function()앞에 async 붙이기.
// 비동기 함수, Promise 활용(군더더기가 많은 코드)
function myPromise() {
    return new Promise((resolve, reject) => {
        resolve("🍎");
    })
}
console.log(myPromise());
------------------------------------------------------

// 비동기 함수, async 활용(담백한 코드로 개선)
// 프로미스를 반환
async function myAsync() {
    return "🍎"; // resolve("🍎")와 같음
}
console.log(myAsync());

2. await 란

  • 비동기 처리 결과를 기다리게 함
  • async 함수 내부에서만 사용 가능
  • 프로미스 체이닝을 간결하게 개선(가독성 증가)
// 비동기 함수
function carrotPromise() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("🥕");
        }, 1000);
    })
}

Promise

// 요리하기: 당근 => 스프
function cookCarrotSoup() {
    carrotPromise()
        .then((carrot) => {
            console.log(`[${carrot}] 스프를 만들었어요`);
        });
}
cookCarrotSoup();

async와 await

// async와 await로 코드를 개선
async function cookCarrotSoup() {
    const carrot = await carrotPromise();
    console.log(`[${carrot}] 스프를 만들었어요`)
}
cookCarrotSoup();

3. try-catch-finally 구문

  • 예외 처리를 위한 구문
  • 예외란, 특정 코드가 수행에 실패한 것
  • 프로미스 체이닝에서,
    then-catch-finally와 같은 개념

비동기 함수에 if문 추가.

// 비동기 함수
function carrotPromise() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if(Math.random() < 0.5) {
                resolve("🥕");
            } else {
                 reject("🍎");
            }
        }, 1000);
    })
}

async function에 try-catch문 추가.

async function cookCarrotSoup() {
    try { // 정상 수행하길 기대하는 코드
         const carrot = await carrotPromise();
         console.log(`[${carrot}] 스프를 만들었어요`)
    } catch(err) { // 예외 발생시, 처리할 코드
        console.log(`요리 실패: ${err}으로 스프를?`);
    } finally { // 무조건 수행할 코드
        console.log("== 끝 ==");
    }
}
cookCarrotSoup();

async 함수의 반환값

반환값이 프로미스이기 때문에 체이닝 호출도 가능하다.

cookCarrotSoup()
    .then()
    .catch()
    .finally();

전체코드

<script>
// 비동기 함수, Promise 활용(군더더기가 많은 코드)
function myPromise() {
    return new Promise((resolve, reject) => {
        resolve("🍎");
    })
}
console.log(myPromise());

// 비동기 함수, async 활용(담백한 코드로 개선)
// 프로미스를 반환
async function myAsync() {
    return "🍎"; // resolve("🍎")와 같음
}
console.log(myAsync());

// 비동기 함수
function carrotPromise() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if(Math.random() < 0.5) {
                resolve("🥕");
            } else {
                 reject("🍎");
            }
        }, 1000);
    })
}

// 요리하기: 당근 => 스프
function cookCarrotSoup() {
    carrotPromise()
        .then((carrot) => {
            console.log(`[${carrot}] 스프를 만들었어요`);
        });
}
cookCarrotSoup();

// async와 await로 코드를 개선
async function cookCarrotSoup() {
    try { // 정상 수행하길 기대하는 코드
         const carrot = await carrotPromise();
         console.log(`[${carrot}] 스프를 만들었어요`)
    } catch(err) { // 예외 발생시, 처리할 코드
        console.log(`요리 실패: ${err}으로 스프를?`);
    } finally { // 무조건 수행할 코드
        console.log("== 끝 ==");
    }
}
// 반환값이 프로미스이기 때문에 체이닝 호출도 가능하다.
cookCarrotSoup()
    .then()
    .catch()
    .finally();
</script>

0개의 댓글