ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 오늘의 궁금증타파(promise)
    hustle 2020. 11. 25. 04:35

    발단 전개 절정 결말

     

    발단

    fetch(newsURL)과 fetch(weatherURL)의 결과를 한 객체에 담아야했다.

     

    function getNewsAndWeather() {
      return new Promise((resolve,reject)=>{
        let obj = {}
        fetch(newsURL)
        .then(param=>{
          return param.json()
        })
        .then(param=>{
          obj.news = param.data
          return fetch(weatherURL)
        })
        .then(param=>{
          return param.json()
        })
        .then(param=>{
          obj.weather = param
        })
        .then(()=>{
          resolve(obj)
        })
      })
    }

    Promise.all을 사용하지 않고는 이렇게 스무스하게 지나갔다.

     

    전개

     

     

    function getNewsAndWeatherAll() {
      let obj = {};
      return new Promise((resolve,reject)=>{
        Promise.all([fetch(newsURL),fetch(weatherURL)])
        .then(param=>{
          return param.map((ele)=>{
            return ele.json()
          })
        })
        .then(param=>{
          return param.map((ele)=>{
            return ele.json()
          })
        })
        .then(param=>{
          obj.news = param[0].data;
          obj.weather = param[1]
        })
        .then(()=>{
          resolve(obj)
        })
      })
      // TODO: Promise.all을 이용해 작성합니다
    }

    나는 promise.all에는 promise객체를 넣으면 된다고 알고있었고

    첫번째 문제도 fetch(newsURL)을 json()한것이기 때문에 이게 맞을줄 알았다..

    console로 하나하나 찍어보니 첫번째 문제는 response였다가 json을 하니 일반객체가 되는데..

    두번째 문제에서는 response였다가 별안간 또 promise가 되어버려서 해결이 안됐다

     

    절정

     

    정 답답해서 이전에 풀었던 코드를 봤다.

    function getNewsAndWeatherAll() {
      let newsFetch = fetch(newsURL).then(response => response.json())
      let weatherFetch = fetch(weatherURL).then(response => response.json())
    
    
      return new Promise((resolve,reject)=>{
        Promise.all([newsFetch,weatherFetch])
        .then(response =>{
          let result = {};
          result.news = response[0].data;
          result.weather = response[1];
          resolve(result)
        })
      })
      // TODO: Promise.all을 이용해 작성합니다
    }
    

    json()한걸 왜 Promise.all에 넣는지 도무지 이해가 안갔다...............

    위에거랑 머가 다르냐구..............................................................................................

     

    헐 이해갔었는데 지금 또 말로 풀어서 설명하려니 머리깨진다.....

    우선 담문제 풀어야지......

     

    까먹기전에 동기분의 귀여운 설명 추가..해두기..

     

    'hustle' 카테고리의 다른 글

    2020.11.27 공부일기를 빙자한 아무말  (0) 2020.11.27
    오늘의 궁금증 타파(node server/JSON)  (0) 2020.11.26
    11.25  (0) 2020.11.25
    하이  (0) 2020.11.20
    가상리액트  (0) 2020.11.18

    댓글

Designed by Tistory.