김주희

비동기 함수 순서 수정

...@@ -4,8 +4,8 @@ const secret_key_traffic = require('../keys/api_option_traffic').key; ...@@ -4,8 +4,8 @@ const secret_key_traffic = require('../keys/api_option_traffic').key;
4 4
5 const requesting = require('request'); 5 const requesting = require('request');
6 6
7 -const lat = "37.54922931758";//"37.239795"; //weather 위도 7 +const lat = "37.54922931758"; //weather 위도
8 -const lon = "126.913415969472";//"127.083240"; //weather 경도 8 +const lon = "126.913415969472"; //weather 경도
9 const sido_num = "11"; //traffic 법정동 시도 코드 9 const sido_num = "11"; //traffic 법정동 시도 코드
10 const gugun_num = "440"; //traffic 법정동 시군구 코드 - 합정동 일대 10 const gugun_num = "440"; //traffic 법정동 시군구 코드 - 합정동 일대
11 const search_year = "2018074"; //traffic 검색을 원하는 연도 11 const search_year = "2018074"; //traffic 검색을 원하는 연도
...@@ -42,17 +42,18 @@ module.exports = (server, app) => { ...@@ -42,17 +42,18 @@ module.exports = (server, app) => {
42 json: true 42 json: true
43 }, 43 },
44 //api에게 응답 받았을때 실행되는 callback function 44 //api에게 응답 받았을때 실행되는 callback function
45 - function (err, api_res, api_body) { 45 + function (err1, api_res1, api_body1) {
46 //err 존재시 promise reject 호출 46 //err 존재시 promise reject 호출
47 - if (err) reject(err); 47 + if (err1) reject(err1);
48 48
49 // api의 response이 있을경우 promise resolve 호출 49 // api의 response이 있을경우 promise resolve 호출
50 - if (api_res) { 50 + if (api_res1) {
51 console.log("calling weather api"); 51 console.log("calling weather api");
52 - resolve(api_body); 52 + resolve(api_body1);
53 } 53 }
54 }); 54 });
55 - }) 55 +
56 + }) //Promise
56 } 57 }
57 58
58 59
...@@ -63,12 +64,6 @@ module.exports = (server, app) => { ...@@ -63,12 +64,6 @@ module.exports = (server, app) => {
63 requesting.get({ 64 requesting.get({
64 // api를 요청할 주소 -- 시크릿키,위도,경도 입력 65 // api를 요청할 주소 -- 시크릿키,위도,경도 입력
65 url: `http://apis.data.go.kr/B552061/${cate1}/${cate2}?ServiceKey=${secret_key_traffic}&searchYearCd=${search_year}&siDo=${sido_num}&guGun=${gugun_num}&type=json&numOfRows=1&pageNo=1`, 66 url: `http://apis.data.go.kr/B552061/${cate1}/${cate2}?ServiceKey=${secret_key_traffic}&searchYearCd=${search_year}&siDo=${sido_num}&guGun=${gugun_num}&type=json&numOfRows=1&pageNo=1`,
66 - //나중에 삭제 http://apis.data.go.kr/B552061/frequentzoneLg/getRestFrequentzoneLg?ServiceKey=XOLqI9tY4gVCdk1i2BoOM3EYmSUYqt8WlXUfIDSfD4RnNBrFwwthbNAtGOxoskP540JbUAzcnuABsydoE2U2dA%3D%3D&searchYearCd=2017&siDo=11&guGun=200&type=json&numOfRows=10&pageNo=1
67 - //나중에 삭제 http://apis.data.go.kr/B552061/frequentzoneLg/getRestFrequentzoneLg?ServiceKey=XOLqI9tY4gVCdk1i2BoOM3EYmSUYqt8WlXUfIDSfD4RnNBrFwwthbNAtGOxoskP540JbUAzcnuABsydoE2U2dA%3D%3D&searchYearCd=2018074&siDo=11&guGun=440&type=json&numOfRows=10&pageNo=1
68 - //sido = 11 gugun = 440 (마포구 합정동, 도화동, 도화동)
69 - //cate1 = frequentzoneLg
70 - //cate2 = getRestFrequentzoneLg
71 - //xml: true
72 json: true 67 json: true
73 }, 68 },
74 //api에게 응답 받았을때 실행되는 callback function 69 //api에게 응답 받았을때 실행되는 callback function
...@@ -82,104 +77,117 @@ module.exports = (server, app) => { ...@@ -82,104 +77,117 @@ module.exports = (server, app) => {
82 resolve(api_body); 77 resolve(api_body);
83 } 78 }
84 }); 79 });
85 - }) 80 + }) //Promise
86 } 81 }
87 82
88 const API_bundle = async () => { 83 const API_bundle = async () => {
89 -
90 try { 84 try {
91 - Current_Weather = await req_API("current", "minutely"); //현재날씨 (분별) //when, what 85 + var order = 0;
92 - Sensible_T = await req_API("index", "wct"); //체감온도 86 + while (order < 2) {
93 - Heat_index = await req_API("index", "heat"); //열지수 87 + switch (order) {
94 - Discomport_index = await req_API("index", "th"); //불쾌지수 88 + case 0:
95 - Ultra_Violet_index = await req_API("index", "uv"); //자외선지수 89 + console.log("APIWait - WAITING FOR ALL API");
96 - 90 + Current_Weather = await req_API("current", "minutely"); //현재날씨 (분별) //when, what
97 - Current_TrafficAcc = await req_API_traffic("frequentzoneLg", "getRestFrequentzoneLg"); //cate1, cate2 91 + Sensible_T = await req_API("index", "wct"); //체감온도
98 - 92 + Heat_index = await req_API("index", "heat"); //열지수
99 - info = { 93 + Discomport_index = await req_API("index", "th"); //불쾌지수
100 - heat: Heat_index.weather.wIndex.heatIndex[0].current.index, //열지수 94 + Ultra_Violet_index = await req_API("index", "uv"); //자외선지수
101 - sensible_temperature: Sensible_T.weather.wIndex.wctIndex[0].current.index, //체감온도 95 + Current_TrafficAcc = await req_API_traffic("frequentzoneLg", "getRestFrequentzoneLg"); //cate1, cate2
102 - discomport: Discomport_index.weather.wIndex.thIndex[0].current.index, //불쾌지수 96 + order = 1;
103 - UV: Ultra_Violet_index.weather.wIndex.uvindex[0].day01.index, //자외선지수 97 + break;
104 - windspd: Current_Weather.weather.minutely[0].wind.wspd, //바람 속도 98 + case 1:
105 - sky: Current_Weather.weather.minutely[0].sky.code, //하늘 상태 99 + console.log("APIDataProcess - CALLING INFO");
106 - rain: Current_Weather.weather.minutely[0].rain.last24hour, //강수량 100 + info = {
107 - current_temperature: Current_Weather.weather.minutely[0].temperature.tc, //현재 온도 101 + heat: Heat_index.weather.wIndex.heatIndex[0].current.index, //열지수
108 - lightning: Current_Weather.weather.minutely[0].lightning, //현재 낙뢰 102 + sensible_temperature: Sensible_T.weather.wIndex.wctIndex[0].current.index, //체감온도
109 - warning: Current_Weather.common.alertYn, //현재 특보 유무 103 + discomport: Discomport_index.weather.wIndex.thIndex[0].current.index, //불쾌지수
110 - typhoon: Current_Weather.common.stormYn, //현재 태풍 104 + UV: Ultra_Violet_index.weather.wIndex.uvindex[0].day01.index, //자외선지수
111 - time: Current_Weather.weather.minutely[0].timeObservation, // 불러온 시각 105 + windspd: Current_Weather.weather.minutely[0].wind.wspd, //바람 속도
112 - death_prob: 0, //확률 106 + sky: Current_Weather.weather.minutely[0].sky.code, //하늘 상태
113 - death_number: Current_TrafficAcc.items.item[0].dth_dnv_cnt, //사망자 수 107 + rain: Current_Weather.weather.minutely[0].rain.last24hour, //강수량
114 - midhurt_number: Current_TrafficAcc.items.item[0].se_dnv_cnt, //중상자 수 108 + current_temperature: Current_Weather.weather.minutely[0].temperature.tc, //현재 온도
115 - lighthurt_number: Current_TrafficAcc.items.item[0].sl_dnv_cnt, //경상자 수 109 + lightning: Current_Weather.weather.minutely[0].lightning, //현재 낙뢰
116 - occur_number: Current_TrafficAcc.items.item[0].occrrnc_cnt //발생건수 110 + warning: Current_Weather.common.alertYn, //현재 특보 유무
117 - //"spot_cd": "11440001" 111 + typhoon: Current_Weather.common.stormYn, //현재 태풍
118 - } 112 + time: Current_Weather.weather.minutely[0].timeObservation, // 불러온 시각
119 - console.log("API INFO \n", info); 113 + death_prob: 0, //확률
120 - 114 + death_number: Current_TrafficAcc.items.item[0].dth_dnv_cnt, //사망자 수
121 - // ------------------------------ death_prob 정의 ------------------------------ 115 + midhurt_number: Current_TrafficAcc.items.item[0].se_dnv_cnt, //중상자 수
122 - 116 + lighthurt_number: Current_TrafficAcc.items.item[0].sl_dnv_cnt, //경상자 수
123 - info.death_prob += info.sky.substr(5) * 1 //하늘 상태에 따라 확률 증가 117 + occur_number: Current_TrafficAcc.items.item[0].occrrnc_cnt //발생건수
124 - 118 + //"spot_cd": "11440001"
125 - if (info.lightning === 1) //낙뢰시에 확률 증가 119 + }
126 - info.death_prob += 1.5; 120 + console.log("API INFO \n", info);
127 - if (info.typhoon === "Y") //태풍시에 확률 증가 121 +
128 - info.death_prob += 1.5; 122 + // ------------------------------ death_prob 정의 ------------------------------
129 - if (info.warning === "Y") // 특보 발령시 확률 증가 123 +
130 - info.death_prob += 1 124 + info.death_prob += info.sky.substr(5) * 1 //하늘 상태에 따라 확률 증가
131 - 125 +
132 - //죽을 확률 계산(내맘대로 커스텀) 126 + if (info.lightning === 1) //낙뢰시에 확률 증가
133 - info.death_prob = ( 127 + info.death_prob += 1.5;
134 - (info.heat / 50) + (Math.abs(info.sensible_temperature - 15) / 10) + (info.discomport / 10) + (info.UV / 10) 128 + if (info.typhoon === "Y") //태풍시에 확률 증가
135 - + info.windspd * 1 + (info.rain / 10) + (Math.abs(info.current_temperature - 15) / 10) 129 + info.death_prob += 1.5;
136 - + (info.death_number / 60) + (info.midhurt_number / 80) + (info.lighthurt_number / 90) + (info.occur_number / 90) 130 + if (info.warning === "Y") // 특보 발령시 확률 증가
137 - ); 131 + info.death_prob += 1
138 - 132 +
139 - //이벤트 기반으로 일정 시간 간격으로 클라이언트에게 보낼 정보, 홈페이지 그래프에 나타날 정보 133 + //죽을 확률 계산(내맘대로 커스텀)
140 - client_send = { 134 + info.death_prob = (
141 - time: info.time, 135 + (info.heat / 50) + (Math.abs(info.sensible_temperature - 15) / 10) + (info.discomport / 10) + (info.UV / 10)
142 - wind: info.windspd, 136 + + info.windspd * 1 + (info.rain / 10) + (Math.abs(info.current_temperature - 15) / 10)
143 - temperature: info.current_temperature, 137 + + (info.death_number / 60) + (info.midhurt_number / 80) + (info.lighthurt_number / 90) + (info.occur_number / 90)
144 - rain: info.rain, 138 + );
145 - death: info.death_prob, 139 +
146 - trafficdeath: info.death_number, 140 + //이벤트 기반으로 일정 시간 간격으로 클라이언트에게 보낼 정보, 홈페이지 그래프에 나타날 정보
147 - mhurt: info.midhurt_number, 141 + client_send = {
148 - lhurt: info.lighthurt_number, 142 + time: info.time,
149 - occurence: info.occur_number 143 + wind: info.windspd,
150 - }; 144 + temperature: info.current_temperature,
151 - function getRandom_add_prob(min, max) { 145 + rain: info.rain,
152 - return Math.random() * (max - min) + min; 146 + death: info.death_prob,
153 - } 147 + trafficdeath: info.death_number,
154 - 148 + mhurt: info.midhurt_number,
155 - 149 + lhurt: info.lighthurt_number,
156 - // 심장이 크게 뛰며 확률이 증가하거나 감소 할 수 있음 150 + occurence: info.occur_number
157 - Math.random() * 2 >= 1 ? client_send.death += getRandom_add_prob(0, 5) : client_send.death -= getRandom_add_prob(0, 5); 151 + };
158 - 152 + function getRandom_add_prob(min, max) {
159 - 153 + return Math.random() * (max - min) + min;
160 - //운명의 장난으로 죽을 확률이 증가하거나 감소함 154 + }
161 - const rand = Math.floor(Math.random() * 6) //생년월일 중 한자리 뽑음 155 +
162 - 156 +
163 - Destiny = client_birth.charAt(rand) / 3; //명시적 형 변환 157 + // 심장이 크게 뛰며 확률이 증가하거나 감소 할 수 있음
164 - if (Destiny == 0) Destiny = 1; //사용자 잘못 입력했을때 예외처리 158 + Math.random() * 2 >= 1 ? client_send.death += getRandom_add_prob(0, 5) : client_send.death -= getRandom_add_prob(0, 5);
165 - Math.random() * 2 >= 1 ? client_send.death += Destiny : client_send.death -= Destiny; 159 +
166 - 160 +
167 - 161 + //운명의 장난으로 죽을 확률이 증가하거나 감소함
168 - //만약 날이 너무 안좋아서 확률이 100을 넘긴다면 100으로 예외처리 162 + const rand = Math.floor(Math.random() * 6) //생년월일 중 한자리 뽑음
169 - if (client_send.death >= 100) { 163 +
170 - client_send.death = 100; 164 + Destiny = client_birth.charAt(rand) / 3; //명시적 형 변환
171 - } 165 + if (Destiny == 0) Destiny = 1; //사용자 잘못 입력했을때 예외처리
172 - 166 + Math.random() * 2 >= 1 ? client_send.death += Destiny : client_send.death -= Destiny;
173 - console.log("client send data \n", client_send) 167 +
174 - 168 +
175 - app.get("socket").emit("weather_and_traffic_Info_minutely_send_to_client", client_send); // 클라이언트에게 정보 담아서 이벤트 발산 169 + //만약 날이 너무 안좋아서 확률이 100을 넘긴다면 100으로 예외처리
176 - console.log("emit"); 170 + if (client_send.death >= 100) {
177 - 171 + client_send.death = 100;
178 - //db에 저장 172 + }
179 - sql = "INSERT INTO apisInfo (time,wind,temperature,rain,prob,tdeath,mhurt,lhurt,occurence) VALUES (?,?,?,?,?,?,?,?,?)"; 173 +
180 - db_total.query(sql, [client_send.time, client_send.wind, client_send.temperature, client_send.rain, client_send.death, client_send.trafficdeath, client_send.mhurt, client_send.lhurt, client_send.occurence], (err, result) => { 174 + console.log("client send data \n", client_send)
181 - if (err) console.log(err); 175 +
182 - }) 176 + app.get("socket").emit("weather_and_traffic_Info_minutely_send_to_client", client_send); // 클라이언트에게 정보 담아서 이벤트 발산
177 + console.log("emit");
178 +
179 + //db에 저장
180 + sql = "INSERT INTO apisInfo (time,wind,temperature,rain,prob,tdeath,mhurt,lhurt,occurence) VALUES (?,?,?,?,?,?,?,?,?)";
181 + db_total.query(sql, [client_send.time, client_send.wind, client_send.temperature, client_send.rain, client_send.death, client_send.trafficdeath, client_send.mhurt, client_send.lhurt, client_send.occurence], (err, result) => {
182 + if (err) console.log(err);
183 + })
184 + order = 2;
185 + break;
186 + default:
187 + order = 3;
188 + break;
189 + }//switch
190 + }; //while
183 191
184 } catch (err) { //promise err or try err catch 192 } catch (err) { //promise err or try err catch
185 console.log("================Error Occured !!================\n", err); 193 console.log("================Error Occured !!================\n", err);
......