async/await 정리

Sheryl Yun·2022년 10월 16일
0
post-thumbnail

기본 프로미스 예시

fetch

fetch('https://api.github.com/users/Yena-Yun')
	.then((res) => {
    	return res.json(); // 응답을 json 형식으로 반환
    }).then((res) => {
    	console.log(res); // 성공 시 데이터 출력
    }).catch((err) => {
    	console.log(err); // 실패 시 오류 출력
    });

new Promise

function walk(amount) {
	return new Promise((resolve, reject) => {
    	// amount가 500 미만이면 reject 문구 출력 후 종료
    	if (amount < 500) {
        	reject("the value is too small");
        }
        
        // amount 시간 뒤에 resolve의 문구 출력
        setTimeout(() => resolve(`you walked for ${amount}ms`), amount);
    });
}

walk(1000).then((res) => {
	console.log(res);
    return walk(700); // 700초 후 resolve 반환 (you walked for 700ms)
}).then((res) => {
	console.log(res);
    return walk(400); // reject 반환 후 종료 (uncaught exception: the value is too small)
    // catch를 쓰지 않았기 때문에 앞에 'uncaught exception:'이 붙는다
}).then((res) => {
	console.log(res);
    return walk(100); // reject 이후의 then은 출력되지 않는다
});

async/await로 변환

async/await로 바꾸려면 다음과 같은 단계가 필요하다.

  1. async를 붙인 비동기 함수 선언
  2. 안에서 함수를 호출할 때 앞에 await 붙이기
  3. then 모두 지우기
  4. 선언한 비동기 함수 호출
function walk(amount) {
	return new Promise((resolve, reject) => {
    	if (amount < 500) {
        	reject("the value is too small");
        }

        setTimeout(() => resolve(`you walked for ${amount}ms`), amount);
    });
}

// 비동기 함수 선언
async function go() {
	const res = await walk(1000); // async가 있어야 await 사용 가능
    console.log(res);
    const res2 = await walk(700); // resolve 출력
    console.log(res2);
    const res3 = await walk(400); // reject 출력 후 종료
    console.log(res3);
    const res4 = await walk(100);
    console.log(res4);
}

// 비동기 함수 호출
go();

async/await의 오류 처리

기본 프로미스 코드와 마찬가지로 try/catch 문을 사용한다.

async function asyncFunc() {
	try {
    	const response = await fetch(URL);
    } catch(err) {
    	console.log(err);
    }
}

asyncFunc(); // TypeError: failed to fetch
profile
데이터 분석가 준비 중입니다 (티스토리에 기록: https://cherylog.tistory.com/)

0개의 댓글