我对JavaScript非常陌生,作为我目前的任务,我将使用openweathermap.org API创建一个简单的天气预报站点。我的任务要求规定,我必须能够通过只输入一个城市名称来获取天气数据。但是,openweather要求在请求URL中包含纬度和经度。预测API调用URL为:https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&exclude={part}&appid={API key}。对于这个URL,我想我会写:
let forecastApiUrl = 'http://api.openweathermap.org/data/2.5/onecall?lat=' + lat + '&lon=' + lon + '&exclude=minutely&appid={TopSecretApiKey}';
幸运的是,openweathermap也有一个GeoCoding API!对GeoCoding的API调用是:https://api.openweathermap.org/geo/1.0/direct?q={city名称}{国家代码}{国家代码}&limit={限制}&appid={API键}。我还没有为此编写URL变量。
我的问题是:如何编写函数,以便GeoCoding API响应的内容将被预测API调用“读取”,并输出我想要的天气预报?这只是我的第二个API练习,也是我做过的唯一一个需要这个额外步骤的练习。任何建议都很感激。请考虑到我是个极端的新手。
发布于 2022-08-12 22:44:57
这个问题最好用承诺来解决。
您可以只需异步等待您的第一个geocaching请求,一旦完成,您将发送第二个请求来获取天气。
它看起来像这样(PSEUDOCODE):
function fetchGeoData() {
return new Promise((resolve, reject) => {
//Check if your request was successful, if it was resolve(), else reject()
})
}
async function fetchWeather() {
const geoData = await fetchGeoData();
And now you can just fetch your weather here, the payload would look something like:
{lat: geoData.lat, long: getData.long}
}不要忘了构建备份,以防任何请求失败。
https://stackoverflow.com/questions/73340367
复制相似问题