자바스크립트 복습 - 11

Stulta Amiko·2022년 5월 19일
0

자바스크립트 복습

목록 보기
11/12
post-thumbnail

async / await

async function 선언은 AsyncFunction객체를 반환하는 하나의 비동기 함수를 정의합니다. 비동기 함수는 이벤트 루프를 통해 비동기적으로 작동하는 함수로, 암시적으로 Promise를 사용하여 결과를 반환합니다. 그러나 비동기 함수를 사용하는 코드의 구문과 구조는, 표준 동기 함수를 사용하는것과 많이 비슷합니다.

function walk(amount) {
    return new Promise((resolve, reject) => {
        if (amount < 500) {
            reject("value is too small");
        }
        setTimeout(() => resolve(`you walked for ${amount}ms`), amount);
    });
}

walk(1000).then(res => {
    console.log(res);
    return walk(500);
}).then(res => {
    console.log(res);
    return walk(700);
}).then(res => {
    console.log(res);
    return walk(800);
}).then(res => {
    console.log(res);
    return walk(400);
}).then(res => {
    console.log(res);
    return walk(600);
});

실행결과
you walked for 1000ms
you walked for 500ms
you walked for 700ms
you walked for 800ms
node:internal/process/promises:246
triggerUncaughtException(err, true / fromPromise /);
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "value is too small".] {
code: 'ERR_UNHANDLED_REJECTION'
}

평범한 프로미스 코드다 하지만 500ms보다 작으면 오류를 출력하도록 출력했기때문에
walk(400)을 하는순간 오류를 던지면서 실행이 종료된다.

async()/await()을 사용해보자

function walk(amount) {
    return new Promise((resolve, reject) => {
        if (amount < 500) {
            reject("value is too small");
        }
        setTimeout(() => resolve(`you walked for ${amount}ms`), amount);
    });
}

async function go() {
    const res = await walk(500);
    console.log(res);
    const res2 = await walk(900);
    console.log(res2);
    const res3 = await walk(600);
    console.log(res3);
    const res4 = await walk(700);
    console.log(res4);
    const res5 = await walk(400);
    console.log(res5);
    const res6 = await walk(500);
    console.log(res6);
}

실행결과
you walked for 1000ms
you walked for 500ms
you walked for 700ms
you walked for 800ms
node:internal/process/promises:246
triggerUncaughtException(err, true / fromPromise /);
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "value is too small".] {
code: 'ERR_UNHANDLED_REJECTION'
}

보면 동일하게 작동하는것을 알 수 있다.
await 키워드는 비동기 함수 내에서만 작동한다.
await 키워드는 프로미스가 결과를 반환할 때 까지 기다리도록 지시한다.
만약 await를 비동기 함수 밖에서 사용하려고 하면 오류가 발생한다.

일반적인 프로미스에서는 .catch()를 이용해서 프로미스가 반환하는 오류들을 처리한다. async/await에서도 비슷하다.

async function asyncFunc() {
    try {
        let response = await fetch('your-url');
    } catch (err) {
        console.log(err);
    }
}

asyncFunc();

실행결과
ReferenceError: fetch is not defined

이런식으로 try-catch를 이용해서 오류를 잡을 수 있다.

0개의 댓글