Today I reviewed and tried to redo my codes I wrote in the past pair programming session. It was about how to use fetch module in javascript. It was quite tricky but I learned a lot!
Using basic Chaining
var newsURL = 'http://localhost:5000/data/latestNews';
var weatherURL = 'http://localhost:5000/data/weather';
function getNewsAndWeather() {
const result = {};
return fetch(newsURL)
.then((newsData) => newsData.json())
.then((newsJson) => {
result.news = newsJson.data
return fetch(weatherURL)
})
.then((weatherData) => weatherData.json())
.then((weatherJson) => {
result.weather = weatherJson
return result;
})
// TODO: fetch을 이용해 작성합니다
// TODO: 여러개의 Promise를 then으로 연결하여 작성합니다
}
if (typeof window === 'undefined') {
module.exports = {
getNewsAndWeather
}
}
Using 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(([news, weather]) => Promise.all([news.json(), weather.json()]))
.then(([news, weather]) => ({news: news.data, weather}))
}
// return Promise.all([fetch(newsURL), fetch(weatherURL)])
// .then(([news, weather]) => Promise.all([news.json(), weather.json()]))
// .then(([news, weather]) => ({news: news.data, weather}))
if (typeof window === 'undefined') {
module.exports = {
getNewsAndWeatherAll
}
}
Using asyncAwait
var newsURL = 'http://localhost:5000/data/latestNews';
var weatherURL = 'http://localhost:5000/data/weather';
async function getNewsAndWeatherAsync() {
const news = await fetch(newsURL).then((news) => news.json());
const weather = await fetch(weatherURL).then((weather) => weather.json());
return { news: news.data, weather: weather }
}
// const news = await fetch(newsURL).then((data1) => data1.json());
// const weather = await fetch(weatherURL).then((data2) => data2.json());
// return { news: news.data, weather: weather };
if (typeof window === 'undefined') {
module.exports = {
getNewsAndWeatherAsync
}
}