我想获取当前天气给定地点的状况为了实现这一点,我使用了两个api。第一个是Mapbox,我用它将地名地理编码为地理坐标,第二个是Accuweather API。我还使用了Axios模块,以便使HTTP请求
为了避免回调地狱和多层代码,并使其更易于阅读和维护,我编写了3个函数:
- cityToCoordinates 获取纬度经度和地点/城市名称。
- coordinatesToPlaceID 获取位置ID的坐标,使用Accuweather
- placeIDToCurrentForecast 获取当前天气
我让这三个函数异步,因为axios请求使用Promises.
问题在placeIDToCurrentForecast函数,其中回调的响应>> >调用后的函数coordinatesToPlaceIDalwaysundefined尽管请求已成功发出,并且我打印了一个响应。
脚本如下:
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
为什么响应未定义,我如何改进的代码吗?
您在coordinatesToPlaceID
函数中返回undefined
,请检查。此外,如果使用then
,则可以避免使用async-await
,反之亦然
const coordinatesToPlaceID = (cityName) => {
const coordinatesToPlaceApiURL = "http://dataservice.accuweather.com/locations/v1/cities/geoposition/search";
const accuWeatherApiKey = "ACCUWEATHER_API_KEY";
return cityToCoordinates(cityName).then((response) => {
const query = `${response.latitude},${response.longitude}`;
const queryUrlEncoded = encodeURIComponent(query);
return 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);
});
});
};