Promise와 async/await은 JavaScript에서 비동기 처리를 위한 패턴
Promise
비동기 작업의 최종 완료나 실패를 나타내는 객체
.then(), .catch(), .finally() 메서드를 통해 결과 처리
async/await
Promise를 기반으로 하는 신택스 슈가(=더 쉽게 코드를 작성할 수 있도록 설계된 문법)
비동기 코드를 마치 동기 코드처럼 작성 가능
async 함수 내에서 await 키워드를 사용하여 Promise의 결과를 기다릴 수 있음
주요 차이점
1. 코드 스타일: async/await이 더 동기적으로 보이는 코드 작성 가능
2. 에러 처리: Promise는 .catch()를 사용, async/await은 try/catch 사용
// Promise
fetchData()
.then(result => {
// 성공 처리
})
.catch(error => {
// 에러 처리
});
// async/await
async function getData() {
try {
const result = await fetchData();
// 성공 처리
} catch (error) {
// 에러 처리
}
}
3. 병렬 처리: Promise는 Promise.all 등을 통해 더 직관적인 병렬 처리 가능
// Promise
Promise.all([
fetchUser(1),
fetchUser(2),
fetchUser(3)
])
.then(users => console.log(users));
// async/await
async function getUsers() {
const userPromises = [
fetchUser(1),
fetchUser(2),
fetchUser(3)
];
const users = await Promise.all(userPromises);
console.log(users);
}
'기술면접' 카테고리의 다른 글
클로저(Closure) (0) | 2024.10.02 |
---|---|
let, const, var의 차이점 (0) | 2024.10.02 |
JavaScript에서 this (0) | 2024.10.02 |
프레임워크, 라이브러리 (0) | 2024.10.02 |
동기 처리, 비동기 처리 (0) | 2024.10.02 |