2032.03.28 홍팍(유튜브) JS async-await
기존에 콜백지옥을 체이닝기법(프로미스)를 이용해 개선했다.

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

// 비동기 함수, 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(() => {
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();
비동기 함수에 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();

반환값이 프로미스이기 때문에 체이닝 호출도 가능하다.
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>