문제상황:
다음과 같은 코드를 작성하여, 사용자 정보를 가져오는 API를 호출한 후, 가져온 사용자 정보를 화면에 표시하려 했습니다.
function getUserInfo(userId) {
const apiUrl = `https://api.example.com/users/${userId}`;
fetch(apiUrl)
.then(response => response.json())
.then(data => {
console.log(data);
document.getElementById('userInfo').innerText = JSON.stringify(data);
});
}
getUserInfo(1);
그러나 다음과 같은 에러로그가 발생했습니다.
TypeError: Cannot read property 'then' of undefined
해결방법:
다음과 같이 코드를 수정하여 에러를 해결했습니다.
async function getUserInfo(userId) {
const apiUrl = `https://api.example.com/users/${userId}`;
try {
const response = await fetch(apiUrl); // 수정된 부분
const data = await response.json(); // 수정된 부분
console.log(data);
document.getElementById('userInfo').innerText = JSON.stringify(data);
} catch (error) {
console.error('Error fetching user info:', error);
}
}
getUserInfo(1);
원인분석:
원인은 fetch 함수가 Promise를 반환하는데, 이를 제대로 처리하지 못한 것입니다. JavaScript에서 비동기 처리를 할 때, Promise와 async/await를 사용할 수 있습니다. 기존 코드에서는 Promise를 사용했지만, 이를 제대로 처리하지 못해 에러가 발생한 것입니다. 수정된 코드에서는 async/await를 사용하여 비동기 처리를 올바르게 구현하였습니다.
참고링크:
728x90