如何将Fetch请求获取的Lat和Lon存入变量供其他Fetch调用
解决方法
要获取并存储纬度(lat)和经度(lon)供后续请求使用,核心是处理fetch的异步特性,让GetCords能返回数据供外部调用。以下是具体修改方案:
1. 修改GetCords函数,返回Promise
fetch是异步操作,需要让GetCords返回Promise,这样外部才能拿到请求结果:
var convertToCords = { Key: "c9676e6950f05e39b2aae36c413d9dff", GetCords: function (cityname) { // 返回fetch的Promise链,方便外部获取结果 return fetch( `https://api.openweathermap.org/geo/1.0/direct?q=${cityname}&limit=1&appid=${this.Key}` ) .then((response) => { if (!response.ok) { throw new Error('请求失败'); } return response.json(); }) .then((data) => { // 直接提取lat和lon返回,简化外部处理 if (data.length === 0) { throw new Error('未找到目标城市'); } return { lat: data[0].lat, lon: data[0].lon }; }); }, // 示例:用坐标发起后续请求的方法 fetchWeather: function(lat, lon) { return fetch( `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${this.Key}` ) .then(response => response.json()) .then(weatherData => { console.log('天气数据:', weatherData); return weatherData; }); } }
2. 调用并存储坐标,再发起后续请求
方式1:链式调用写法
// 获取坐标后,直接发起后续请求 convertToCords.GetCords("london") .then((coords) => { // 把坐标存入变量,按需使用 const { lat, lon } = coords; console.log('纬度:', lat, '经度:', lon); // 调用另一个请求 return convertToCords.fetchWeather(lat, lon); }) .catch((error) => { console.error('错误:', error); });
方式2:async/await写法(更直观)
async function getCityInfo(cityName) { try { // 等待坐标请求完成 const coords = await convertToCords.GetCords(cityName); const { lat, lon } = coords; console.log('纬度:', lat, '经度:', lon); // 用坐标发起天气请求 const weatherData = await convertToCords.fetchWeather(lat, lon); // 处理返回的天气数据 console.log('天气结果:', weatherData); } catch (error) { console.error('出错了:', error); } } // 执行函数 getCityInfo("london");
关键说明
- 必须让
GetCords返回Promise,否则外部无法获取异步操作的结果 - API返回的是数组(
data[0]),因为设置了limit=1,所以取第一个元素提取坐标 - 加入错误处理(请求失败、未找到城市),避免程序崩溃
内容的提问来源于stack exchange,提问作者RAlN4
相关产品推荐
相关产品推荐

