Fetch 사용 시 Return값 받기

HOONEY·2022년 1월 28일
1

Javascript

목록 보기
2/8
post-thumbnail

원인

  • jQuery에서 벗어나고자 $.ajax 대신 fetch를 사용하는데, return값을 console.log로 찍어보면 계속 response가 찍혔다.
fetch(url).then(function(response) {
  return response.json();
}).catch(function(error) {
  // Error
  console.error(error);
});;
  • 공부한대로 이렇게 하면 되지만, fetch를 따로 함수로 만들어서 사용하는 상황
const result = await fetchFunction(url, method, parameter);
console.log(result); // response가 찍힘.

해결방안

  • await를 한번 더 해서 json()처리 하면 간단히 해결.
const response = await fetch(url, method, parameter);
const result = await response.json();
console.log(result);
profile
기록하는 블로그

0개의 댓글