React.js
를 공부하던 중fetch
로 서버와 통신하는 방법을 보았는데, 콜백함수와 프로미스 등 js개념이 부족해 fetch를 깊게 이해하기가 어려워생활코딩 - Promise(callback & async)
를 통해 javascrpt에 대한 이해를 넓히고자 한다.
console.log(1);
console.log(2);
console.log(3);
console.log(4);
1
2
3
4
console.log(1);
console.log(2);
setTimeout(function(){console.log(3)}, 5000) // 5초가 지난 후에 콜백 함수 실행
console.log(4);
1
2
4
3 -> 프로그램과 상관없이 독립적으로 실행됨
만약 동기적으로 통신할 경우, 통신이 완료될때까지 사용자는 아무 행위도 할 수 없음!
하지만 사용자는 통신을 하고있다는 사실조차 알수가 없는데, 이는 비동기적으로 통신을 했기 때문이다.
브라우저와 웹서버가 통신할때 자주 사용하는 fetch API
는 프로미스를 사용
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json()) // 얻게된 데이터타입이 json임을 알려줌
.then((data) => console.log(data)); // 데이터 불러오기
fetch
: json 데이터 타입을 JavaScript의 데이터 타입으로 바꾸어 줌console.log(1);
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json()) // 얻게된 데이터타입이 json임을 알려줌
.then((data) => console.log(data)); // 데이터 불러오기
console.log(2);
1
2
{100} [{...},{...},{...},{...}, ...]
then
이 프로미스
fetch()
함수는Promise
데이터 타입을 리턴한다. 이Promise
데이터 타입은Response
객체를 돌려 줄 것이다.
Promise
를 리턴한다면, 그 함수는 비동기 함수일 가능성이 매우 높다.then
과 catch
는 둘 다 콜백 함수를 받고, 파라미터를 하나씩 가지고 있음fetch
를 통해 실행한 결과가 성공했을 때 then
으로 전달된 콜백함수가 호출fetch
를 통해 실행한 결과가 실패했을 때 catch
안으로 전달된 콜백함수가 호출console.log(1);
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json()) // 얻게된 데이터타입이 json임을 JavaScript에게 알려줌
.then((data) => console.log(data)); // 데이터 불러오기
console.log(2);
fetch('https://jsonplaceholder.typicode.com/posts')
.then(function(response){
console.log(response.json());
})
response.json()
는 무엇을 리턴할까?