1. 먼저 서버 실행시킨다.
//package.json에 들어가보면 아래와 같이 나와있다.
"scripts": {
"server:part-3": "node part-3/__test__/app.js"
}
//즉, npm run server:part-3을 하게되면 node part-3/__test__/app.js가 실행되는 것
app.js가 서버로 실행된다.
[app.js 파일]
//HTTP 요청을 처리하고 응답을 보내 주는 프로그램을 웹 서버(Web Server).
//node.js의 http 모듈을 이용해 웹 서버를 만듭니다.
//express에서는 http모듈 사용 x.
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
const data = {
"data": [
{ "row_id": 2, "title": "2021년 경제 성장률 전망 밝아", "source": "A신문", "timestamp": "2020/12/30" },
{ "row_id": 3, "title": "코로나19 증가추세 대폭 하락해", "source": "BBC", "timestamp": "2020/12/29" },
{ "row_id": 4, "title": "코드스테이츠 취업연계 파트너사 xxx건 돌파", "source": "스타트업 뉴스", "timestamp": "2020/12/31" }
]
};
app.get('/data/latestNews', async (req, res) => {
res.status(200).json(data)
});
app.get('/data/weather', async (req, res) => {
res.status(200).json({ "status": "sunny", "temperature": "28", "fineDust": "good" });
});
const server = app.listen(5000);
console.log('http://localhost:5000/data/latestNews 에서 뉴스를 얻을 수 있습니다');
console.log('http://localhost:5000/data/weather 에서 날씨를 얻을 수 있습니다');
module.exports = {
app,
server
}
1. Promise Chaining 사용
function getNewsAndWeather() {
const newsURL = 'http://localhost:5000/data/latestNews';
const weatherURL = 'http://localhost:5000/data/weather';
return fetch(newsURL) //1. newURL을 통해 fetch로 요청
.then((resp) => resp.json()) //2. json형태의 response를 json()메소드를 통해 parsing.
.then((json1) => { // 2.response를 parsing한 것 : json1
return fetch(weatherURL) // 3. 또, weatherURL을 통해 fetch로 요청
.then((resp) => resp.json()) // 4. json형태의 response를 json()메소드를 통해 parsing.
.then((json2) => { // 4.response를 parsing한 것 : json2
return {
news: json1.data,
weather: json2,
};
});
});
}
2. Promise.all 사용
function getNewsAndWeatherAll() {
const newsURL = 'http://localhost:5000/data/latestNews';
const weatherURL = 'http://localhost:5000/data/weather';
return Promise.all([fetch(newsURL), fetch(weatherURL)])
//Promise.all에는 [] 배열이 들어가고, 그 배열의 요소는 Promise 객체 또는 값이 들어온다.
.then(([newsResponse, weatherResponse]) => { //각각 Promise객체의 resolve값
return Promise.all([newsResponse.json(), weatherResponse.json()]);
}) //Promise.all의 [] 배열의 요소는 값이 들어간 상태.
.then(([json1, json2]) => {
return {
news: json1.data,
weather: json2,
};
});
//MDN예제
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'foo');
});
// promise.all의 인자로 순회 가능한 요소를 배열 안에 담아 인자로 준다.
Promise.all([promise1, promise2, promise3]).then((values) => {
// 추후 해당 비동기 결과 값들을 담은 배열을 then의 인자로 받을 수 있다.
console.log(values);
});
// expected output: Array [3, 42, "foo"]
}
3. async / await
async function getNewsAndWeatherAsync() {
const newsURL = 'http://localhost:5000/data/latestNews';
const weatherURL = 'http://localhost:5000/data/weather';
const json1 = await fetch(newsURL).then((resp) => resp.json());
//fetch(newsURL).then((resp) => resp.json()) --> Promise객체
//await 뒤에는 Promise객체가 들어오고, 그 Promise객체의 resolve값이 변수에 담긴다.
//일종의 resolve값이 resp.json(). resolve값이 다음 then인자로 들어가기때문.
//json1 = resp.json()
const json2 = await fetch(weatherURL).then((resp) => resp.json());
//json2 = resp.json()
return {
news: json1.data,
weather: json2,
};
}
'JavaScript' 카테고리의 다른 글
스코프 checkpoint 문제 (0) | 2022.03.04 |
---|---|
SPA란? (0) | 2022.02.21 |
fetch() API (0) | 2021.09.21 |
callback vs promise vs async & await (0) | 2021.09.20 |
타이머 API ( setTimeout, setInterval, clearInterval) (0) | 2021.09.19 |