실패한 나의 코드
// 커피 목록 조회 API를 요청해주세요.
let result;
const getCoffee = () => {
console.log("index.js 파일의 openMenu 함수 안에서 getCoffee가 실행 됨");
// 1. 백엔드 서버로 /starbucks API 요청해 커피 데이터를 받는다.
axios.get("http://localhost:3000/starbucks").then((res) => {
console.log(res);
console.log(res.data);
result = res.data;
console.log(result[0]);
});
// 2. 받은 데이터로 createMenuCard 함수를 이용해 메뉴 카드를 모두 만들어주세요.
for (let i = 0; i < result.length; i++) {
createMenuCard(result[i]);
}
};
실패원인
▶ 코드에서 오류가 발생하는 이유는 axios.get() 메소드가 비동기로 작동하기 때문이다.
▶ axios.get()을 실행하면, 서버로부터 데이터를 요청하는 과정이 시작되지만,
▶ 데이터를 응답받는데 걸리는 시간동안에는 for문이 실행됩니다.
▶ 따라서 for문에서 result라는 변수를 사용할 때는 아직 데이터가 로드되지 않아서 undefined 오류가 발생한다.
수정해서 성공한 코드
// 커피 목록 조회 API를 요청해주세요.
let result;
const getCoffee = () => {
console.log("index.js 파일의 openMenu 함수 안에서 getCoffee가 실행 됨");
// 1. 백엔드 서버로 /starbucks API 요청해 커피 데이터를 받는다.
axios.get("http://localhost:3000/starbucks").then((res) => {
// console.log(res);
// console.log(res.data);
result = res.data;
// console.log(result[0]);
// 2. 받은 데이터로 createMenuCard 함수를 이용해 메뉴 카드를 모두 만들어주세요.
for (let i = 0; i < result.length; i++) {
createMenuCard(result[i]);
}
});
};
▶ axios.get 함수의 구현부에 for문을 넣는다.
'고농축 백엔드' 카테고리의 다른 글
고농축 백엔드 7 - docker 명령어 정리 (0) | 2023.01.22 |
---|---|
고농축 백엔드 6 - 동기와 비동기 (0) | 2023.01.22 |
고농축 백엔드 5 - graphql 연습2 (0) | 2023.01.18 |
고농축 백엔드4 -GraphQL 2 (0) | 2023.01.18 |
고농축 백엔드 3 - GraphQL★★ (0) | 2023.01.18 |