32일차, 비동기 fetch API

2021. 9. 1. 20:56
반응형

2021. 09. 01 수요일

1. Today's Key points!🔑

  • fetch

2. 정리해보자!🧹

비동기 요청의 가장 대표적인 사례는 네트워크 요청이다. 네트워크를 통해 이뤄지는 요청은 그 형태가 다양한데 그 중에서 URL로 요청하는 경우가 가장 흔하다. URL로 요청하는 걸 가능하게 해주는 API가 바로 fetch API이다. 특정 URL로부터 정보를 받아오는 역할을 한다. 이 과정이 비동기로 이루어지기 때문에, 경우에 따라 다소 시간이 걸릴 수 있다. 

fetch 사용법 

1
2
3
4
5
let url = 'url주소';
fetch(url)
  .then((response) => response.json()) //자체적으로 json() 메소드가 있어, 응답을 parsing시켜서 다음 Promise로 전달한다.
  .then((json) => console.log(json)) // 콘솔에 json을 출력
  .catch((error) => console.log(error)); // 에러 발생시 에러를 띄운다.
cs

3. Sprint과제 복기🧐

👉🏻basicChaining

1
2
3
4
5
6
7
8
9
10
11
12
13
function getNewsAndWeather() {
  let obj = {}; //빈 객체를 만들어서 여기에 채워줄 것이다.
  return fetch(newsURL) //newsURL을 받아와서
    .then((response) => response.json()) //parsing 시켜주고
    .then((json) => {
      obj.news = json.data // obj에 news속성으로 담아준다.
      return fetch(weatherURL)}) // 그리고 weatherURL을 받아와서
    .then((response) => response.json()) //위와 같이 처리를 해주고
    .then((json) => {
      obj.weather = json
      return obj // 정보를 담은 객체를 리턴한다.
  })
}
cs

근데 위의 코드를 보면 return 위에 let obj = {};이 있고, return안에서 모든걸 처리해서 위의 obj에 넣어준다는 것이 불안정할 수 있다고 한다. 그래서 다시 코드를 짜보았다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function getNewsAndWeather() {  
  return fetch(newsURL) //newsURL을 받아서
    .then((response) => response.json()) //parsing 시켜주고
    .then((json1) => {
      return fetch(weatherURL) //weatherURL을 받아서
        .then((response) => response.json())//parsing 시켜주고
        .then((json2) => {
          return { // 객체안에 모아서 리턴해준다.
            news : json1.data, 
            weather : json2
          };
        })
      });
    }
cs

👉🏻PromiseAll

1
2
3
4
5
6
7
8
9
10
11
function getNewsAndWeatherAll() {
  let news = fetch(newsURL).then((res) => res.json()); //newsURL을 받아서 parsing처리를 해준것을 news에 할당
  let weather = fetch(weatherURL).then((res) => res.json()); //weatherURL을 받아서 parsing처리를 해준것을 weather에 할당
 
  return Promise.all([news, weather]) //Promise.all로 한꺼번에 처리
  .then((value) => {
    const news = value[0].data;
    const weather = value[1];
    return {news, weather}  
    })
}
cs

그런데 만약 news, weather처럼 URL을 받아서 json처리해줘야할 데이터가 100개라면?? 번거롭게 일일이 다 할당시켜줘야하니까 비효율적일 것이다. 그래서 코드를 다시짜보았다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function getNewsAndWeatherAll() {
  let fetches = [fetch(newsURL), fetch(weatherURL)]; //fetch로 URL을 받은 것을 배열에 다 모은다.
  //여기서 console.log(fetches)를 해보면 [Promise, Promise]라는 결과를 볼 수 있을 것이다.
 
  return Promise.all(fetches).then(fetched => { //Promise.all로 한번에 처리를 해줄 것이다.
//Promise.all을 해주면 resolve된 값이 된다. console.log(fetched)를 해보면 [Response, Response]라는 결과를 볼 수 있다.
    
    const parsed = fetched.map(el => el.json()); //전부 parsing처리를 해준다.
//console.log(parsed) 의 결과로 [Promise, Promise]가 되는 것을 볼 수 있다.
    
    return Promise.all(parsed); //parsing처리된 데이터들을 넘겨줄 것이다. 근데 여기서 Promise.all을 한번더 사용하는 이유는
//json처리를 하면서 다시 Promise가 되었기 때문에(위의 콘솔로그 참고) 다시 resolve된 값으로 바꿔주기위해 Promise.all을 한번 더 사용해준다.
  }).then(parsed => {
    const news = parsed[0].data;
      const weather = parsed[1];
      return {news, weather}
    })
}
cs

👉🏻AsyncAwait

1
2
3
4
5
async function getNewsAndWeatherAsync() {
  const json1 = await fetch(newsURL).then((value) => value.json());
  const json2 = await fetch(weatherURL).then((value) => value.json());
  return {news: json1.data, weather: json2}
}
cs

이렇게 sync await을 사용하면 편하다고 Promise.all을 사용할 수 있는 경우에 이렇게 사용하면 오히려 더 비효율적인 방법이 될 수 있다. 예를 들어 받아와야할 데이터가 100개 이상이라고 한다면, 일일이 다 await을 쓰고있어야 할 것이다. 그래서 위의 Promise.all을 사용한 것중에 배열에 담아서 사용하는 것처럼 해주면 비동기적으로 한번에 처리해서 처리시간을 크게 줄일 수 있을 것이다.

반응형
LIST

BELATED ARTICLES

more