async / await는 “시간이 걸리는 작업의 결과를 기다려야 할 때” 사용합니다.
자바스크립트는 기본적으로 비동기 언어입니다.
console.log("A");
setTimeout(() => console.log("B"), 1000);
console.log("C");
출력:
A
C
B
👉 기다려주지 않습니다.
➡️ 결과가 오기 전에는 다음 작업을 하면 안 되는 것들
“이 함수 안에는 기다려야 할 작업이 있다”
“이 줄의 작업이 끝날 때까지 기다려라”
async function example() {
const result = await something();
console.log(result);
}
function login() {
const res = fetch("/login");
console.log(res); // Promise
}
👉 아직 결과 안 옴
👉 Promise 객체만 출력
async function login() {
const res = await fetch("/login");
const data = await res.json();
console.log(data);
}
👉 서버 응답을 받은 뒤 실행
await로 기다리는 동안 실패할 수 있기 때문
async function login() {
try {
const res = await fetch("/login");
const data = await res.json();
return data;
} catch (error) {
alert("서버 오류");
}
}
💡 비동기 함수의 에러 처리는 try-catch로만 잡힌다
| 상황 | async/await |
|---|---|
| 서버 요청 | ✅ |
| 외부 API | ✅ |
| 파일 업로드 | ✅ |
| 토큰 검사 | ✅ |
| 계산 | ❌ |
| 배열 map/filter | ❌ |
| includes / if | ❌ |
| 즉시 결과 나오는 함수 | ❌ |
// ❌ 에러
const data = await fetch(url);
👉 반드시 async 함수 안에서만 사용
async function getData() {
const data = await fetch(url);
}
“그냥 then 쓰면 안 돼?”
fetch(url)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err));
vs
try {
const res = await fetch(url);
const data = await res.json();
} catch {}
👉 실무에서는 async/await가 압도적으로 선호
async function handleLogin(id, pw) {
try {
const res = await fetch("/login", { method: "POST" });
if (!res.ok) {
return "아이디 또는 비밀번호 오류"; // 정상 흐름
}
const user = await res.json(); // 기다려야 함
saveUser(user);
} catch {
alert("네트워크 오류"); // 비정상 흐름
}
}
“결과를 기다려야 하면 async / await”
그리고
iftry-catchasync/await