我只是想从地理位置API获取纬度和经度,以便将数据传递到另一个API调用中以获取天气。我该如何将这些值分配给全局变量?截至目前,我变得不确定。
我已经将变量移入和移出了函数。试图返回函数内的值并导出函数本身。
const https = require('https');
const locationApiKey =
"KEY GOES HERE";
let lat;
let lon;
let cityState;
module.exports = location = https.get(`https://api.ipdata.co/?api-key=${locationApiKey}`, response => {
try {
let body = " ";
response.on('data', data => {
body += data.toString();
});
response.on('end', () => {
const locationData = JSON.parse(body);
// console.dir(locationData);
lat = locationData.latitude;
lon = locationData.longitude;
});
} catch (error) {
console.error(error.message);
}
});
module.exports.lat = lat;
module.exports.lon = lon;
答案 0 :(得分:0)
要导出异步调用检索的某些值,您需要将它们包装在Promise或callback中。
使用promise样式,它将看起来像这样
// File: api.js
module.exports = () => new Promise((resolve, reject) => {
https.get(`https://api.ipdata.co/?api-key=${locationApiKey}`, response => {
try {
let body = " ";
response.on('data', data => {
body += data.toString();
});
response.on('end', () => {
const { latitude, longitude } = JSON.parse(body);
resolve({lat: latitude, lon: longitude});
});
} catch (error) {
reject(error);
}
});
});
然后您可以获取“包裹” 值
// File: caller.js
const getLocation = require('./api.js');
getLocation()
.then(({lat, lon}) => {
// The values are here
console.log(`Latitude: ${lat}, Longitude: ${lon}`)
}))
.catch(console.error);