프론트엔드/Javascript
Javascript - async/await와 try/catch
0-SIK
2024. 10. 25. 20:48
728x90
1. async/await의 역할
- async: 비동기 함수임을 명시합니다. 이 함수 내부에서 await를 사용할 수 있습니다.
- await: Promise가 해결될 때까지 기다립니다. 코드가 동기적으로 작성된 것처럼 보이게 해줍니다.
예시 (async/await 사용)
const getData = async () => {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
};
위 코드에서는 **await**를 사용해 Promise가 해결될 때까지 기다립니다. 이로 인해 코드가 순차적으로 진행되며, 비동기 처리를 더 쉽게 이해할 수 있습니다.
2. try/catch로 에러 처리
비동기 함수에서는 네트워크 오류, API 응답 실패 등 여러 에러가 발생할 수 있습니다. try/catch를 사용해 이러한 에러를 효율적으로 처리합니다.
예시 (try/catch와 async/await 사용)
const getData = async () => {
try {
const response = await fetch("https://api.example.com/data");
if (!response.ok) throw new Error("Failed to fetch data");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching data:", error);
}
};
- try 블록에서 비동기 작업을 수행합니다.
- 만약 에러가 발생하면 즉시 catch 블록으로 넘어갑니다.
- catch 블록에서 에러 메시지를 로깅하거나 적절히 처리합니다.
3. async/await과 try/catch를 사용하는 이유
1. 가독성 개선:
- 기존의 .then() 체인과 비교하면, 코드가 더 직관적으로 보입니다.
- async/await는 동기 코드처럼 작성할 수 있어 이해하기 쉽습니다.
// 예시 (.then() 체인과 비교)
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error fetching data:", error));
2. 에러 처리의 통일성:
- 동기 함수와 동일한 방식으로 에러를 처리할 수 있습니다. (try/catch)
- 비동기 코드에서도 에러 흐름을 명확하게 제어할 수 있습니다.
3. 비동기 코드의 디버깅 용이:
- .then() 체인에서는 어느 지점에서 에러가 발생했는지 추적하기 어렵지만, async/await와 try/catch를 사용하면 에러 위치를 명확히 파악할 수 있습니다.
728x90