TIL28, fetch
fetch API는 URL을 이용해서 네트워크 요청을 가능하게 해주는 API이다.
const url = "https://test.com";
fetch(url)
.then((response) => response.json())
.then((result) => console.log(result))
위와 같은 코드를 작성하면, url로 선언한 웹사이트를 fetch에 전달해주고,
전달받은 data를 자체적으로 존재하는 json()를 이용해 JSON 형태로 변환시켜서 다음 promise에 전달한다.
기본적으로 Chaining하는 방식을 알아보자
let gameURL = 'https://game.com'
let eduURL = 'https://edu.com'
const obj = {};
function getGameAndEdu () {
return fetch(gameURL)
.then((response) => response.json())
.then((game) => {
obj.game = game;
return fetch(eduURL)
})
.then((response) => response.json())
.then((edu) => {
obj.edu = edu;
return obj;
})
}
예제이기 때문에, 각각의 url에서 무엇을 받아오는지 알 수는 없지만,
각각 원시자료형만을 값으로 가지는 객체를 받아온다고 가정했을때
최종적으로 return되는 obj는 아래와 같다.
{
game: {gameURL이 갖고 있는 정보},
edu: {eduURL이 갖고 있는 정보}
}