実現したいこと
OpenWeatherMapのAPIを使い天気を取得する処理をopenweather.js
ファイルにしてmain.js
からrequire
して使いたい。
バージョン等
OS: Windows10 Pro 64bit
エディタ: Atom 1.38.2 x64
Node.js: v10.16.0
yarn: 1.16.0
現状
ファイル構造
JS_WARBot ├─ lib │ └─ openweather.js ├─ node_modules │ └─ ... ├─ package.json ├─ main.js └─ yarn.lock
コード
main.js
node.js
1const openweather = require('./lib/openweather.js') 2 3cityid = "6940394" 4 5async function getweather(cityid){ 6 let result = await openweather.get(cityid); 7 console.log(result); 8} 9getweather(cityid);
./lib/openweather.js
node.js
1const http = require('http'); 2var APIKEY = "***************"; 3 4function get(cityid) { 5 var URL = 'http://api.openweathermap.org/data/2.5/forecast?id='+ cityid +'&units=metric&lang=ja&APPID='+ APIKEY; 6 console.log(URL); 7 function getPromise(URL){ 8 return new Promise((resolve, reject)=>{ 9 http.get(URL, function(res) { 10 let body = ''; 11 res.setEncoding('utf8'); 12 13 res.on('data', function(chunk) { 14 body += chunk; 15 }); 16 17 res.on('end', function(chunk) { 18 res = JSON.parse(body); 19 20 var day_num = 0; 21 var day = "今日"; 22 23 if (res.list[day_num].rain !== undefined) { 24 var result = `:umbrella2: ${day}の天気予報 :sun_with_face:\n\n天気: ${res.list[day_num].weather[0].description}\n` 25 +`雨量: 3時間あたり${res.list[day_num].rain["3h"]}mm\n最低気温: ${res.list[day_num].main.temp_min}℃\n` 26 +`最高気温: ${res.list[day_num].main.temp_max}℃\n\n` 27 +`:small_orange_diamond:この天気は${day}のこの時間の天気を表示しています。\n他の時間の天気はこちら :point_right: https://openweathermap.org/city/${res.city.id}\n\n` 28 +`:open_file_folder: 天気データ提供: openweathermap.org` 29 resolve(result); 30 } else { 31 var result = `:umbrella2: ${day}の天気予報 :sun_with_face:\n\n天気: ${res.list[day_num].weather[0].description}\n` 32 +`最低気温: ${res.list[day_num].main.temp_min}℃\n最高気温: ${res.list[day_num].main.temp_max}℃\n\n` 33 +`:small_orange_diamond:この天気は${day}のこの時間の天気を表示しています。\n他の時間の天気はこちら :point_right: https://openweathermap.org/city/${res.city.id}\n\n` 34 +`:open_file_folder: 天気データ提供: openweathermap.org`; 35 resolve(result); 36 } 37 }) 38 }) 39 }) 40 } 41 getPromise(URL).then(result => { 42 console.log(result); 43 return result; 44 }) 45 46} 47 48module.exports.get = get;
起こっている問題
openweather.js
のconsole.log
では正常なデータが表示されるのですが、main.js
のconsole.log
ではundefined
となってしまいます。
インターネットでは、この手の問題はPromise等をと使えば解決できるとのことですが、一向に解決できないので質問させていただきます。
よろしくお願い致します。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。