비동기 작업을 마치 동기처럼 순차적으로 처리할 수 있게 만들어주는 문법!
async function getData() {
const result = await fetchData(); // fetchData가 끝날 때까지 기다림
console.log(result); // 결과 출력
}
기존의 Promise .then() 체인은 이렇게 생겼어:
fetchData()
.then(res => processData(res))
.then(final => console.log(final))
.catch(err => console.error(err));
이걸 async/await를 사용하면 이렇게 변신! 👇
async function main() {
try {
const res = await fetchData();
const final = await processData(res);
console.log(final);
} catch (err) {
console.error(err);
}
}
→ 가독성 향상! 순서가 눈에 딱 보여!
즉, await는 Promise의 결과(resolve된 값)를 기다렸다가
결과를 변수처럼 다룰 수 있게 해주는 것이야.
const result = await somePromise; ← 이 한 줄이 핵심!
console.log("1");
async function fetchSomething() {
console.log("2");
await new Promise(res => setTimeout(res, 1000));
console.log("3");
}
fetchSomething();
console.log("4");
// 출력:
// 1
// 2
// 4
// 3
→ 즉, async 함수 안은 순차적으로 실행되지만,
→ 밖의 코드는 기다려주지 않음! (비동기!)
doSomething()
.then(res => {
console.log("1", res);
return nextStep(res);
})
.then(next => {
console.log("2", next);
});
.then() 체인도 비동기 결과를 순서대로 처리
그래서 사람들이 "동기처럼 흐름을 탄다"고 표현
하지만 실제로는 콜백 기반 비동기 처리야
| 개념 | 설명 |
|---|---|
Promise | 비동기 결과를 표현하는 객체 |
.then() | 비동기 결과를 받아서 순차적으로 처리 |
async/await | Promise를 더 읽기 쉽게 처리하는 문법 |
await | Promise가 끝날 때까지 기다린 뒤 결과를 받아옴 |
| 밖의 코드 | 여전히 비동기 흐름! await가 멈추지 않음 |