ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JS] ์‹ค์Šต - fetch API
    codeStates front-end/Java Script 2023. 1. 19. 17:35
    ๋ฐ˜์‘ํ˜•

     

     

     

     

    ๐Ÿ“Œ fetch API

     

     

     

    ๐Ÿ“– ํ•™์Šต ๋ชฉํ‘œ

     

     

    Part 3๋Š” Node.js ํ™˜๊ฒฝ์„ ๋– ๋‚˜, ๋ธŒ๋ผ์šฐ์ €์—์„œ ์ง„ํ–‰ํ•ฉ๋‹ˆ๋‹ค. Node.js ํ™˜๊ฒฝ์—๋Š” fetch API๊ฐ€ ๋‚ด์žฅ ๋ชจ๋“ˆ๋กœ ์ œ๊ณต๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

    ์ด๋ฒˆ์—๋Š” fetch๋ฅผ ์ด์šฉํ•ด HTTP ์š”์ฒญ์„ ๋ณด๋‚ด๊ณ , ์‘๋‹ต์„ ๋ฐ›๋Š” ์—ฐ์Šต์„ ํ•ฉ๋‹ˆ๋‹ค. Part 3๋Š” Part 2์™€ ๋น„์Šทํ•˜๊ฒŒ ๊ตฌ์„ฑ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ๋‹ค๋งŒ callback ํ˜•ํƒœ์˜ ์š”์ฒญ์ด ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฏ€๋กœ, chaining๊ณผ Promise.all ๊ทธ๋ฆฌ๊ณ  async/await์„ ์ด์šฉํ•ฉ๋‹ˆ๋‹ค.

    npm run server:part-3 ์œผ๋กœ ์„œ๋ฒ„๋ฅผ ์‹คํ–‰ํ•ด url์„ ํ†ตํ•ด ์ •๋ณด๋ฅผ ์–ป์–ด ์˜ฌ ์ˆ˜ ์žˆ์—ˆ๋‹ค

     

     

    1. Chaining Test

     

    var newsURL = 'http://localhost:5000/data/latestNews';
    var weatherURL = 'http://localhost:5000/data/weather';
    
    function getNewsAndWeather() {
     // TODO: fetch์„ ์ด์šฉํ•ด ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค
     // TODO: ์—ฌ๋Ÿฌ๊ฐœ์˜ Promise๋ฅผ then์œผ๋กœ ์—ฐ๊ฒฐํ•˜์—ฌ ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค
     return fetch(newsURL)
     .then(resp => resp.json())
     .then(news => {
       // news๋Š” ๋ฐ›์•„์˜จ newsURL
       return fetch(weatherURL)
       // ๋˜‘๊ฐ™์€ ์ž‘์—… ํ•œ๋ฒˆ ๋” ์ง„ํ–‰
         .then(resp => resp.json())
         .then(weather => {
         // ์ด ์Šค์ฝ”ํ”„์—์„œ๋งŒ news, weather ์— ์ ‘๊ทผ ๊ฐ€๋Šฅํ•˜๋‹ค
           return {
             news: news.data,
             weather: weather
           }
         });
       })
    }
    
    if (typeof window === 'undefined') {
     module.exports = {
       getNewsAndWeather
     }
    }

     

    2. promise.all

     

    var newsURL = 'http://localhost:5000/data/latestNews';
    var weatherURL = 'http://localhost:5000/data/weather';
    
    function getNewsAndWeatherAll() {
      return Promise.all([
        fetch(newsURL),
        fetch(weatherURL)
      ])
        .then(([newsResponse, weatherResponse]) => {
          return Promise.all([newsResponse.json(), weatherResponse.json()])
        })
        .then(([news, weather]) => {
          return {
            news: news.data,
            weather: weather
          }
        })
    }
    
    if (typeof window === 'undefined') {
      module.exports = {
        getNewsAndWeatherAll
      }
    }

     

    3. async await

     

    var newsURL = 'http://localhost:5000/data/latestNews';
    var weatherURL = 'http://localhost:5000/data/weather';
    
    async function getNewsAndWeatherAsync() {
    
      let news = await fetch(newsURL).then(resp => resp.json());
      let weather = await fetch(weatherURL).then(resp => resp.json());
    
      return {
        news: news.data,
        weather: weather
      }
    }
    
    if (typeof window === 'undefined') {
      module.exports = {
        getNewsAndWeatherAsync
      }
    }
    ๋ฐ˜์‘ํ˜•

    ๋Œ“๊ธ€

Designed by Tistory.