● 오늘 공부한 것
- fetch, Promise, axios 과제하기
01_basicChaining.js
const newsURL = 'http://localhost:4999/data/latestNews';
const weatherURL = 'http://localhost:4999/data/weather';
function getNewsAndWeather() {
// TODO: fetch을 이용해 작성합니다
// TODO: 여러개의 Promise를 then으로 연결하여 작성합니다
const result = {};
return fetch(newsURL)
.then(response => response.json())
.then(json => {
result.news = json.data;
return fetch(weatherURL);
})
.then(response => response.json())
.then(json => {
result.weather = json;
return result
})
}
02_promiseAll.js
function getNewsAndWeatherAll() {
const newsURL = 'http://localhost:4999/data/latestNews';
const weatherURL = 'http://localhost:4999/data/weather';
// TODO: Promise.all을 이용해 작성합니다
const obj = {}
return Promise.all([fetch(newsURL), fetch(weatherURL)]) // (1)
.then(response => { // (2)
const parsed = response.map(item => item.json()) // (3)
return Promise.all(parsed) // (4)
})
.then(parsed => { //(5)
obj.news = parsed[0].data;
obj.weather = parsed[1];
return obj;
})
}
여기서 나는 Promise.all을 하면 무조건적으로 모든게 배열로 반환된다고 생각했는데, 그게아니었다.
- (1) fetch는 프로미스를 반환한다.
- (1) 따라서 첫번째 줄은 Promise.all([promise, promise]) 과 같다.
- (1)->(2) resolve의 과정을 거친다.
- (2) promise들이 resolve되면서 response 객체가 된다. 즉 [response, response] 가 된다.
- (3) 배열안에 든 response를 돌면서 .json() 메서드를 돌아준다.
- (3) json 데이터 처리를 해주면서 promise를 반환한다.
- (4) parsed는 [promise, promise] 와 같다.
- (5) promise가 resolve되면서 원하는 json 데이터로 바뀐다.
03_asyncAwait.js
const { response } = require('express');
async function getNewsAndWeatherAsync() {
const newsURL = 'http://localhost:4999/data/latestNews';
const weatherURL = 'http://localhost:4999/data/weather';
// TODO: async/await 키워드를 이용해 작성합니다
const json1 = await fetch(newsURL) //
.then(response => response.json())
const json2 = await fetch(weatherURL) //
.then(response => response.json())
return {news : json1.data, weather : json2}
● 내가 놓치고 있던 것
추가 공부한 것..
● 끝맺음
- 느낀점
- 벌써 자바스크립트가 끝났다는게 믿기지가 않는다. 이번주는 진짜 모딥다에서 못읽었던 부분을 마구마구 달리면서 읽었는데, 읽을때마다 어려운 건 사실 같다. 1회독.. 거의 다했고 이번주 내로 진짜로 다 읽었을 것 같은데, 앞으로 스터디를 통해서 복습하는 시간을 스스로 가져야겠다.
- 심볼, 이터러블, 제너레이터에 대한 정리가 확실히 필요하다.
- 수업이외의 학습
- 모듈
- fetch, axios 정리