-
[JS] ์ค์ต - fetch APIcodeStates 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 } }
๋ฐ์ํ'codeStates front-end > Java Script' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JS] chapter23. Tree UI (0) 2023.02.14 [JS] chapter22. ๋น๋๊ธฐ4 - Axios (0) 2023.01.19 [JS] chapter21. ๋น๋๊ธฐ3 - fetch API (0) 2023.01.19 [JS] chapter20. ๋น๋๊ธฐ2 - node.js (0) 2023.01.19 [JS] ์ค์ต - ํ์ด๋จธ API (0) 2023.01.18