我想獲取給定地點的當前天氣狀況。為了實作這一點,我使用了兩個API。第一個是Mapbox,我用它來將地名地理編碼為地理坐標,第二個是Accuweather API。我還使用了 Axios 模塊 來向 API發出HTTP 請求。
為了避免回呼地獄和多層代碼并使其更易于閱讀和維護,我制作了 3 個函式:
- cityToCoordinates獲取地點/城市名稱的經緯度。
- coordinatesToPlaceID使用Accuweather獲取坐標的地點ID
- placeIDToCurrentForecast獲取該地點的當前天氣
由于 axios 請求使用Promises ,我將所有三個函式設為異步。
問題出在placeIDToCurrentForecast函式中,呼叫coordinatesToPlaceID后then函式中的回呼回應始終未定義,盡管請求已成功發出并且我列印了回應。
這是腳本:
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
為什么回應未定義,我該如何改進代碼?
uj5u.com熱心網友回復:
您正在函式中回傳undefined,coordinatesToPlaceID請檢查。此外,如果您正在使用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);
});
});
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/537063.html
