들어가기 전에
JSON이란
객체 리터럴 문법을 따른다. 문자열 형태로 존재한다. 웹 서버에서 데이터를 수신할 때 데이터는 항상 문자열이다!
JSON.parse() : 인수로 전달받은(JSON형식의) 문자열을 자바스크립트 객체로 변환한다.
res.json() : 데이터들을 자동으로 json 형식으로 바꾸어 보낸다.
fetch()의 프로미스는 서버에서 헤더를 포함한 응답을 받는 순간
이행한다.
fetch(url); // Promise{<pending>}
fetch(url).then((res)=>res.json());
1. .then()으로 데이터를 넘겨받는다. (res)
2. 넘겨받은 데이터(res)를 .json()을 이용해 JSON형태로 가져온다.
3. 이 프로미스 객체는 result로 Object를 갖고있다.
Object에는 우리가 찾는 데이터가 담겨져있다.
let result = {}; return fetch(url) .then((res) => res.json()) //Promise 반환 .then((res) => { //res === {data:Array(3)} result.news = res.data; //res.data에 있는 정보를 result.news에 할당 return fetch(url2); //다음 작업에 필요한 데이터를 리턴해줌 }) .then((res) => res.json()) //res를 .json()을 통해 promise 반환. //res.json() === Promise {<pending>} .then((res) => { result.weather = res; //res에 접근해 result의 weather에 할당. return result; })
res.json()은 Promise객체를 반환한다.
body가 나중에 도착하기 때문에 header가 먼저 와서 기다린다!
fetch를 하면 response객체는 header를 바로 보내는데
body가 아직 응답을 하지 않았기 때문에 기다리려고 Promise 객체를 반환하는 것이다.
.then() 체인을 사용해서 Response 응답객체를 파라미터로 전달받는다.
let data1 = fetch(newsURL).then((res)=> res.json());
let data2 = fetch(weatherURL).then((res)=> res.json());
return Promise.all([data1,data2]).then((res) => {
return { news: res[0].data, weather: res[1] };
//객체로 반환. 각각 news, weather에 필요한 객체 값에 접근해 해당 값 할당
});
let news = await fetch(newsURL)
.then((res)=> res.json())
.then((json)=> json.data); //한번 더 가공함!
let weather = await fetch(weatherURL).then((res)=> res.json());
return { news, weather }; //키와 값이 같아서 생략 가능함
//return { news: news, weather: weather };