Promise.all에서 오류

웹 개발/Problems 2021. 3. 19. 11:44

02_promiseAll.js
0.00MB

function getNewsAndWeatherAll() {
  // TODO: Promise.all을 이용해 작성합니다
  let result = {}
  let arr = []
  return Promise.all([fetch(newsURL),fetch(weatherURL)])
  .then(rawDatas =>{
    //console.log('datas: ',rawDatas)
    arr = rawDatas.map((rawData)=>{
      return rawData.json().then(json=>{
        return json
      })
    })
    return arr
  })
  .then(promiseArr =>{
    let dataArr = []
    promiseArr[0]
    .then(data => {
      dataArr.push(data.data)
      return promiseArr[1]
    })
    .then(data=>{
      dataArr.push(data)      
    })
    //console.log('dataArr: ',dataArr)
    return dataArr
  })
  .then(dataArr =>{
    console.log('length: ',dataArr.length)
    console.log('last then dataArr: ',dataArr)
    console.log('dataArr[0]: ', dataArr[0])
    console.log('dataArr[1]: ', dataArr[1])
    result.news = dataArr[0]
    result.weather = dataArr[1]
    return result
  })
}

여기서 실행을 했을때 이상하게 마지막 then에서 받아온 인자 dataArr를 console.log찍어봤는데 undefined가 나온다.

그냥 undefined라면 모를까 두번째 console.log("last then dataArr:", dataArr) 이부분은 또 잘 나온다... 아마 promise.all사용법을 몰라서 이상하게 꼬아서 생기 문제이긴 하지만 참 신기한 문제였다... json(), fetch()와 같은 비동기 함수를 다룰때에는 조심해야겠다.

실행되는 코드:

var newsURL = 'http://localhost:5000/data/latestNews';
var weatherURL = 'http://localhost:5000/data/weather';

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

      return result
    })
}
if (typeof window === 'undefined') {
  module.exports = {
    getNewsAndWeatherAll
  }
}
: