我想获取某个地方的当前天气状况。为了实现这一点,我使用了两个API。第一个是Mapbox,我使用它将地名地理编码为地理坐标,第二个是Accuweather API。我还使用Axios模块向API发出HTTP请求。
为了避免回调地狱和多层代码,并使它更容易阅读和维护,我做了3个函数:
1.cityToCoordinates*以获取地点/城市名称的纬度和经度。
1.***coordinatesToPlaceID使用Accuweather获取坐标的地点ID**
1.*placeIDToCurrentForecast*获取当前天气的地点
由于axios请求使用Promises,所以我将这三个函数都设置为异步。
问题出在placeIDToCurrentForecast函数中,在调用coordinatesToPlaceID之后,then函数中的回调响应始终是undefined,尽管请求已成功发出并且我打印了响应。
下面是脚本:
const axios = require("axios").default || require("axios");
const cityToCoordinates = async (cityName) => {
const geoCodeBaseURL = " https://api.mapbox.com/geocoding/v5/mapbox.places/";
const mapbowAcessToken = "MAPBOX_TOKEN";
const limit = 1;
const cityNameUrlEncoded = encodeURIComponent(cityName);
return await axios
.get(
`${geoCodeBaseURL}${cityNameUrlEncoded}.json?access_token=${mapbowAcessToken}&limit=${limit}`
)
.then((response) => {
const responseObject = response.data;
if (responseObject.features.length === 0) {
console.log("Sorry no such place exists");
return;
} else {
const location = responseObject.features["0"].center;
const longitude = location[0];
const latitude = location[1];
return {
latitude: latitude,
longitude: longitude,
};
}
})
.catch((error) => {
console.log("An error has occured in city to coordinates");
// console.log(error);
});
};
const coordinatesToPlaceID = async (cityName) => {
const coordinatesToPlaceApiURL = "http://dataservice.accuweather.com/locations/v1/cities/geoposition/search";
const accuWeatherApiKey = "ACCUWEATHER_API_KEY";
await cityToCoordinates(cityName).then(async (response) => {
const query = `${response.latitude},${response.longitude}`;
const queryUrlEncoded = encodeURIComponent(query);
return await axios
.get(
`${coordinatesToPlaceApiURL}?q=${queryUrlEncoded}&apikey=${accuWeatherApiKey}`
)
.then((response) => {
console.log(response.data.Key);
return response.data.Key;
})
.catch((error) => {
console.log("An error has occured in coordinates to place ID");
// console.log(error);
});
});
};
const placeIDToCurrentForecast = async (cityName) => {
const placeIdToCurrentWeather = "http://dataservice.accuweather.com/currentconditions/v1/";
const accuWeatherApiKey = "ACCUWEATHER_API_KEY";
await coordinatesToPlaceID(cityName).then(async (response) => {
console.log(response); // Always undefined!!!
if (response) {
const placeId = response;
await axios
.get(`${placeIdToCurrentWeather}${placeId}?apikey=${accuWeatherApiKey}`)
.then((response) => {
console.log(
"The current weathr in " +
cityName +
" is " +
response.data[0].Temperature.Metric.Value +
"° C"
);
})
.catch((error) => {
console.log("An error has occured in place ID to current forecast");
// console.log(error);
});
} else {
console.log("There is no response");
}
});
};
placeIDToCurrentForecast("California");
输出:
332131
undefined
There is no response
为什么响应未定义,我如何改进代码?
1条答案
按热度按时间6qftjkof1#
在
coordinatesToPlaceID
函数中返回undefined
,请检查。另外,如果使用then
,可以避免使用async-await
,反之亦然