Javascript 如何正确导出从NodeJS中的API调用检索到的值
我只是尝试从地理定位API获取纬度和经度,以便将数据传递到另一个API调用以获取天气。如何将值分配给全局变量?到现在为止,我还没有定义 我已经将变量移入和移出函数。试图返回函数中的值并导出函数本身Javascript 如何正确导出从NodeJS中的API调用检索到的值,javascript,node.js,ip-geolocation,Javascript,Node.js,Ip Geolocation,我只是尝试从地理定位API获取纬度和经度,以便将数据传递到另一个API调用以获取天气。如何将值分配给全局变量?到现在为止,我还没有定义 我已经将变量移入和移出函数。试图返回函数中的值并导出函数本身 const https = require('https'); const locationApiKey = "KEY GOES HERE"; let lat; let lon; let cityState; module.exports = location = https.get(`htt
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;
要导出异步调用检索到的某些值,需要将它们包装在或中 使用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);
然后你可以得到像这样的“包装”值
// 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);
http.get
是一种异步方法。您应该将其转换为承诺并在异步函数中等待,或者在回调中使用这些值