DESKTOP-PC6TBNS\강환석씨

The API call result was not normally contained in the (info) object because node…

…js processed the function asynchronously. So we used the following grammar rules, async, await, and changed it to call api synchronously. Good operation
...@@ -11,6 +11,7 @@ module.exports = (server, app) => { ...@@ -11,6 +11,7 @@ module.exports = (server, app) => {
11 11
12 let info = {} 12 let info = {}
13 const CALL = (when, what) => { 13 const CALL = (when, what) => {
14 + return new Promise((resolve, reject) => {
14 requesting.get({ 15 requesting.get({
15 // api를 요청할 주소 -- 시크릿키,위도,경도 입력 16 // api를 요청할 주소 -- 시크릿키,위도,경도 입력
16 url: `https://api2.sktelecom.com/weather/${when}/${what}?appKey=${secret_key}&lat=${lat}&lon=${lon}`, 17 url: `https://api2.sktelecom.com/weather/${when}/${what}?appKey=${secret_key}&lat=${lat}&lon=${lon}`,
...@@ -18,49 +19,64 @@ module.exports = (server, app) => { ...@@ -18,49 +19,64 @@ module.exports = (server, app) => {
18 }, 19 },
19 //api에게 응답 받았을때 실행되는 callback function 20 //api에게 응답 받았을때 실행되는 callback function
20 function (err, api_res, api_body) { 21 function (err, api_res, api_body) {
21 - if (err) throw err; 22 + //err 존재시 promise reject 호출
22 - // api의 대답이 있을경우 실행 23 + if (err) reject(err);
24 +
25 + // api의 response이 있을경우 promise resolve 호출
23 if (api_res) { 26 if (api_res) {
24 - return api_body; 27 + console.log("call");
25 - // api_body.weather.minutely[0] 28 + resolve(api_body);
26 } 29 }
27 }); 30 });
31 + })
28 } 32 }
29 io.on('connection', (socket) => { //웹 페이지 연결시 루프 동작 33 io.on('connection', (socket) => { //웹 페이지 연결시 루프 동작
30 let API_CALL; 34 let API_CALL;
31 - let Current_Weather ={}; 35 + //명시적으로 객체임을 선언
32 - let Sensible_T; 36 + let Current_Weather = {};
33 - let Heat_index={}; 37 + let Sensible_T = {};
34 - let Discomport_index={}; 38 + let Heat_index = {};
35 - let Ultra_Violet_index={}; 39 + let Discomport_index = {};
36 - let sending_to_client_info={}; 40 + let Ultra_Violet_index = {};
37 - let client_send={}; 41 + let sending_to_client_info = {};
42 + let client_send = {};
38 let sql; 43 let sql;
39 44
40 socket.on("connection", () => { 45 socket.on("connection", () => {
41 - API_CALL = setInterval(() => { 46 + console.log("lala");
47 + // API_CALL = setInterval(() => {
48 + console.log("lala");
49 +
50 +
51 + const API_bundle = async () => {
42 52
43 - Current_Weather = CALL("current","minutely"); //현재날씨 (분별) 53 + try {
44 - Sensible_T = CALL("index","wct"); //체감온도 54 + Current_Weather = await CALL("current", "minutely"); //현재날씨 (분별)
45 - Heat_index = CALL("index","heat"); //열지수 55 + Sensible_T = await CALL("index", "wct"); //체감온도
46 - Discomport_index = CALL("index","th"); //불쾌지수 56 + Heat_index = await CALL("index", "heat"); //열지수
47 - Ultra_Violet_index = CALL("index","uv"); //자외선지수 57 + Discomport_index = await CALL("index", "th"); //불쾌지수
58 + Ultra_Violet_index = await CALL("index", "uv"); //자외선지수
59 + console.log("bundle");
48 60
49 info = { 61 info = {
50 - heat : Sensible_T.weather.wIndex.heatIndex[0].current.index, //열지수 62 + heat: Heat_index.weather.wIndex.heatIndex[0].current.index, //열지수
51 - sensible_temperature : Sensible_T.weather.wIndex.wctIndex[0].current.index, //체감온도 63 + sensible_temperature: Sensible_T.weather.wIndex.wctIndex[0].current.index, //체감온도
52 - discomport : Discomport_index.weather.wIndex.thIndex[0].current.index, //불쾌지수 64 + discomport: Discomport_index.weather.wIndex.thIndex[0].current.index, //불쾌지수
53 - UV : Ultra_Violet_index.weather.wIndex.uvindex[0].day00.index, //자외선지수 65 + UV: Ultra_Violet_index.weather.wIndex.uvindex[0].day01.index, //자외선지수
54 - windspd : Current_Weather.weather.minutely[0].wind.wspd, //바람 속도 66 + windspd: Current_Weather.weather.minutely[0].wind.wspd, //바람 속도
55 - sky : Current_Weather.weather.minutely[0].sky.code, //하늘 상태 67 + sky: Current_Weather.weather.minutely[0].sky.code, //하늘 상태
56 - rain : Current_Weather.weather.minutely[0].rain.last24hour, //강수량 68 + rain: Current_Weather.weather.minutely[0].rain.last24hour, //강수량
57 - current_temperature : Current_Weather.weather.minutely[0].temperature.tc, //현재 온도 69 + current_temperature: Current_Weather.weather.minutely[0].temperature.tc, //현재 온도
58 - lightning : Current_Weather.weather.minutely[0].lightning, //현재 낙뢰 70 + lightning: Current_Weather.weather.minutely[0].lightning, //현재 낙뢰
59 - warning : Current_Weather.common.alertYn, //현재 특보 유무 71 + warning: Current_Weather.common.alertYn, //현재 특보 유무
60 - typhoon : Current_Weather.common.stormYn, //현재 태풍 72 + typhoon: Current_Weather.common.stormYn, //현재 태풍
61 - time : Current_Weather.weather.minutely[0].timeObservation, // 불러온 시각 73 + time: Current_Weather.weather.minutely[0].timeObservation, // 불러온 시각
62 - death_prob:0 //확률 74 + death_prob: 0 //확률
63 } 75 }
76 + console.log("callback")
77 + console.log(info);
78 +
79 + // ------------------------------ death_prob 정의 ------------------------------
64 80
65 info.death_prob += info.sky.substr(5)*1 //하늘 상태에 따라 확률 증가 81 info.death_prob += info.sky.substr(5)*1 //하늘 상태에 따라 확률 증가
66 82
...@@ -71,12 +87,13 @@ module.exports = (server, app) => { ...@@ -71,12 +87,13 @@ module.exports = (server, app) => {
71 if(info.warning === "Y") // 특보 발령시 확률 증가 87 if(info.warning === "Y") // 특보 발령시 확률 증가
72 info.death_prob += 5 88 info.death_prob += 5
73 89
74 - //죽을 확률 계산(내맘대로) 90 + //죽을 확률 계산(내맘대로 커스텀)
75 info.death_prob =( 91 info.death_prob =(
76 - (info.heat/8) + (abs(info.sensible_temperature-15)/2) + (info.discomport/10) + (info.UV/5) 92 + (info.heat/8) + (Math.abs(info.sensible_temperature-15)/2) + (info.discomport/10) + (info.UV/5)
77 - + (info.windspd*3) + (info.rain/10) + (abs(info.current_temperature-15)/2) 93 + + (info.windspd*3) + (info.rain/10) + (Math.abs(info.current_temperature-15)/2)
78 ); 94 );
79 95
96 + //이벤트 기반으로 일정 시간 간격으로 클라이언트에게 보낼 정보
80 client_send={ 97 client_send={
81 time : info.time, 98 time : info.time,
82 wind : info.windspd, 99 wind : info.windspd,
...@@ -85,18 +102,29 @@ module.exports = (server, app) => { ...@@ -85,18 +102,29 @@ module.exports = (server, app) => {
85 death : info.death_prob 102 death : info.death_prob
86 }; 103 };
87 104
88 - //db에 저장 105 + //만약 날이 너무 안좋아서 확률이 100을 넘긴다면 100으로 예외처리
89 - sql="INSERT INTO weatherInfo (time,wind,temperature,rain,prob) VALUES (?,?,?,?,?)"; 106 + if(client_send.death>=100){
90 - db.query(sql,[client_send.time,client_send.wind,client_send.temperature,client_send.rain,client_send.death],(err,result)=>{ 107 + client_send.death=100;
91 - if(err) console.log(err); 108 + }
92 - socket.emit("weatherInfo_minutely_send_to_client",client_send); // 클라이언트에게 정보 담아서 이벤트 발산 109 +
93 - }) 110 + console.log(client_send)
94 - }, 60 * 1000); //1분마다 호출 111 + } catch (err) { //promise err or try err catch
112 + console.log("================Error Occured !!================\n",err);
113 + }
114 + }
115 + API_bundle();
116 +
117 + // //db에 저장
118 + // sql="INSERT INTO weatherInfo (time,wind,temperature,rain,prob) VALUES (?,?,?,?,?)";
119 + // db.query(sql,[client_send.time,client_send.wind,client_send.temperature,client_send.rain,client_send.death],(err,result)=>{
120 + // if(err) console.log(err);
121 + // socket.emit("weatherInfo_minutely_send_to_client",client_send); // 클라이언트에게 정보 담아서 이벤트 발산
122 + // })
123 + // }, 1* 1000); //1분마다 호출
95 }); 124 });
96 125
97 socket.on('disconnecting', (reason) => { 126 socket.on('disconnecting', (reason) => {
98 clearInterval(API_CALL); //연결 종료시 해제 127 clearInterval(API_CALL); //연결 종료시 해제
99 }) 128 })
100 }) 129 })
101 -} 130 + }
102 -
......
...@@ -38,20 +38,19 @@ ...@@ -38,20 +38,19 @@
38 ></div> 38 ></div>
39 </div> 39 </div>
40 </div> 40 </div>
41 -<<<<<<< HEAD
42 41
43 <script src="/socket.io/socket.io.js"></script> 42 <script src="/socket.io/socket.io.js"></script>
44 <script> 43 <script>
45 - var socket = io.connect('/'); 44 + var socket = io('http://localhost',{transports: ['websocket']});
46 - socket.emit("connection"); 45 + socket.emit("connection",()=>{
47 - socket.on("weatherInfo_minutely_send_to_cliend",(info)=>{ //서버에서 client에게 메세지 전송 46 + console.log("connected");
47 + });
48 + socket.on("weatherInfo_minutely_send_to_client",(info)=>{ //서버에서 client에게 메세지 전송
48 console.log(info); 49 console.log(info);
49 }); 50 });
50 </script> 51 </script>
51 52
52 -=======
53 53
54 ->>>>>>> 0f5edf6316e2444f5fd2a050fed5e771e5141733
55 <!-- 첫번째 그래프 --> 54 <!-- 첫번째 그래프 -->
56 <script type="text/javascript"> 55 <script type="text/javascript">
57 Highcharts.chart("container1", { 56 Highcharts.chart("container1", {
......