我创建了一个函数来将纬度和经度存储到全局变量中,以便可以将它们作为参数传递给另一个函数,但是我无法使其正常工作。我通过将一个函数放到另一个函数中解决了这个问题,但是对于为什么我原来的方法不起作用感到困惑?
下面的代码来自于getCordinates函数将值传递到getWeather函数中时,这些值不应该存储在全局变量中。
---这里是主应用的星级---
console.log("Server starting")
const yargs = require("yargs");
const geocode = require("./geocode/geocode");
const weather = require("./weather/weather");
const request = require('request');
let cordinates = {
lat: 0,
lng: 0
}
const argv = yargs.options({
a:{
demand: true,
alias: 'address',
describe: 'Address to fetch weather for',
string: true
}
}).help().alias('help', 'h').argv;
geocode.getCordinates(argv.a, (errorMessage, results) => {
if(errorMessage){
console.log(errorMessage);
console.log(results)
}else{
console.log(`${results.address} - ${results.city} ${results.state}, ${results.country}`)
}
});
weather.getWeather(cordinates.lat, cordinates.lng, (errorMessage, weatherResults) => {
if(errorMessage){
console.log(errorMessage);
console.log(results);
} else {
console.log(`The current temperature is ${weatherResults.temp} degrees celcius, and it feels like ${weatherResults.feelsLike}.`)
}
});
---主应用程序到此为止---
--- getCordinates函数从此处开始---
var getCordinates = (address, callback) =>{
request({
url: `http://www.mapquestapi.com/geocoding/v1/address?key=Dfgu2XcWvcvlYAbkz3B8gXr2z6SfTKtO&location=${encodeURIComponent(address)}`,
json: true
}, (error, response, body) => {
if(error){
callback("Unable to connect to mapquest servers.", "Jack make big fart will be passed to the callback function as the results parameter.")
}else if(body.info.statuscode !== 0 && body.info.statuscode !== 200){
callback("This location does not exist, please try again");
} else{
callback(undefined, {
address: body.results[0].providedLocation.location.toUpperCase(),
city:body.results[0].locations[0].adminArea5,
state:body.results[0].locations[0].adminArea3,
country:body.results[0].locations[0].adminArea1,
lat:body.results[0].locations[0].latLng.lat,
long:body.results[0].locations[0].latLng.lng
});
}
});
}
--- getCordinates函数到此结束---
--- getWeather功能从此处开始---
let tempConverter = (farenheit) => {
return Math.round((farenheit - 32) * 5 / 9)
};
let getWeather = (latitude, longitude, callback) =>{
request({
url:`https://api.darksky.net/forecast/d32506e0e791e1ea3d7f55f24f43b2ba/${latitude},${longitude}`,
json:true
}, (error, response, body) => {
if(error){
callback("Unable to connect to forecast.io servers.", error)
}else if(response.statusCode === 400){
callback(body.error)
}else if(response.statusCode === 403){
callback(response.statusCode, response.statusMessage)
}else {
callback(undefined, {
temp: tempConverter(body.currently.temperature),
feelsLike: tempConverter(body.currently.apparentTemperature)
});
}
});
};
编辑:我添加了其他代码。抱歉,我之前没有添加!