회원정보 조회 함수
async function getUser() {
const response = await axios.get("/api/user");
return response.data;
}
getUser 함수 호출
const userPromise = getUser();
const user = await userPromise;
console.log(userPromise);
// Promise { <fulfilled>: { userId: "hong", name: "홍길동" } }
console.log(user);
// { userId: "hong", name: "홍길동" }
=> userPromise는 Promise 객체
=> user는 서버 응답 데이터
* Promise 객체 : 진행 중인/완료된 비동기 작업을 나타내는 객체로,
작업 상태 (pending / fulfilled / rejected)와 완료 후 결과를 내부적으로 관리한다.
await 을 사용해서 결과값을 바로 받으면
const user = await getUser();
console.log(user);
// { userId: "hong", name: "홍길동" }
await 은 Promise가 완료될 때까지 기다렸다가 그 결과를 받아온다.
회원정보 및 공지사항 조회 (순차 실행)
const user = await getUser();
const notices = await getNotice();
회원정보 조회 시작 => 완료 결과를 user로 받음 => 공지사항 조회 시작 => 완료 결과를 notices로 받음.
조회함수가 각각 약 1초씩 소요된다고 하면
회원정보 조회 약 1초 + 공지사항 조회 약 1초 => 전체 소요 시간은 약 2초.
회원정보 및 공지사항 조회 (병렬 실행)
const userPromise = getUser(); // 조회 시작
const noticePromise = getNotice(); // 조회 시작
const user = await userPromise;
const notices = await noticePromise;
회원정보 조회, 공지사항 조회 시작 => userPromise, noticePromise로 반환 => 완료 결과를 user, notices로 받음.
조회함수가 각각 약 1초씩 소요된다고 하면
회원정보 조회와 공지사항 조회가 동시에 시작되기 때문에 전체 소요 시간은 약 1초.
=> Promise로 작업 시작 시점과 결과를 받는 시점을 분리할 수 있음.
Promise.all 활용
const [user, notices] = await Promise.all([
getUser(),
getNotice()
]);
=> 동시에 시작된 여러 개의 Promise를 기다려 모든 작업이 성공하면 결과를 배열로 반환.
하나라도 실패하면 즉시 실패를 반환.
'JavaScript > 공부공부' 카테고리의 다른 글
| [JS / jQuery] 커스텀 select-option 디자인 (0) | 2025.10.18 |
|---|---|
| [JS / jQuery] 동적 요소 이벤트 바인딩 (0) | 2025.07.24 |
| [JS] URL 객체 (0) | 2025.07.15 |
| [JS] event.currentTarget vs event.target (0) | 2025.02.27 |
| [JS] Form & Checkbox (2) | 2024.11.06 |