如何解决Fetch获取Geocoding API数据无法存入变量的问题
解决Fetch获取Geoapify地理编码API数据无法存入变量的问题
问题场景
尝试通过Fetch调用Geoapify地理编码API获取数据,并存入变量以提取经纬度。初始代码如下:
var requestOptions = { method: 'GET', }; fetch("https://api.geoapify.com/v1/geocode/search?text=38%20Upper%20Montagu%20Street%2C%20Westminster%20W1H%201LJ%2C%20United%20Kingdom&apiKey=${MYKEYAPI}", requestOptions) .then(response => response.json()) .then(result => console.log(result)) .then(data=>{jsonData=data;}) .catch(error => console.log('error', error));
(代码中已使用实际API密钥)
遇到的问题:Fetch基于Promise异步执行,无法直接将数据存入变量,仅能在浏览器控制台看到结果。尝试用async/await解决时出现错误:
错误写法1及报错
async function fetchText() { let response = await fetch("https://api.geoapify.com/v1/geocode/search?text=38%20Upper%20Montagu%20Street%2C%20Westminster%20W1H%201LJ%2C%20United%20Kingdom&apiKey=${MYKEYAPI}", requestOptions) .then(response => response.json()) .then(result => console.log(result)) .then(data=>{jsonData=data;}) .catch(error => console.log('error', error)); let data = await response.text(); console.log(data); } fetchText();
报错:
"Uncaught (in promise) TypeError: Cannot read properties of undefined"
错误写法2及结果
async function funcionAsincrona(){ const responses = await fetch("https://api.geoapify.com/v1/geocode/search?text=38%20Upper%20Montagu%20Street%2C%20Westminster%20W1H%201LJ%2C%20United%20Kingdom&apiKey=${MYKEYAPI}", requestOptions) .then(response => response.json()) .then(result => console.log(result)) .catch(error => console.log('error', error)); return responses; } let responses=funcionAsincrona();
responses的值:
Promise {}[[Prototype]]:... "Promise"[[Prototype]]: Object[[PromiseState]]: "fulfilled"[[PromiseResult]]: undefined
解决方案
错误原因分析
- 混合使用
await和.then导致逻辑混乱:.then链中最后一个回调没有返回值,使得await拿到的是undefined,后续调用response.text()自然报错。 .then(result => console.log(result))仅打印结果但未返回result,最终responses为undefined;且异步函数调用后返回的是Promise,必须用await或.then处理才能拿到实际数据。
正确写法1:纯.then链式调用
确保每个.then返回需要的数据,在回调中处理变量赋值和经纬度提取:
var requestOptions = { method: 'GET', }; fetch("https://api.geoapify.com/v1/geocode/search?text=38%20Upper%20Montagu%20Street%2C%20Westminster%20W1H%201LJ%2C%20United%20Kingdom&apiKey=${MYKEYAPI}", requestOptions) .then(response => { // 检查HTTP请求是否成功 if (!response.ok) { throw new Error(`请求失败,状态码:${response.status}`); } return response.json(); }) .then(result => { console.log(result); // 提取经纬度(Geoapify返回结构:features[0].properties包含lat/lon) const { lat, lon } = result.features[0].properties; console.log('纬度:', lat, '经度:', lon); // 将数据存入变量(如需全局变量可赋值给window.jsonData) const jsonData = result; // 后续可在这里使用jsonData return jsonData; }) .catch(error => console.log('error', error));
正确写法2:纯async/await写法
避免混合.then,用try/catch处理错误,逻辑更清晰:
var requestOptions = { method: 'GET', }; async function fetchGeoData() { try { const response = await fetch("https://api.geoapify.com/v1/geocode/search?text=38%20Upper%20Montagu%20Street%2C%20Westminster%20W1H%201LJ%2C%20United%20Kingdom&apiKey=${MYKEYAPI}", requestOptions); if (!response.ok) { throw new Error(`HTTP错误! 状态码: ${response.status}`); } const result = await response.json(); console.log(result); // 提取经纬度 const { lat, lon } = result.features[0].properties; console.log('纬度:', lat, '经度:', lon); // 返回数据供后续使用 return result; } catch (error) { console.log('error', error); throw error; // 可抛出错误让调用者处理 } } // 方式1:在async函数中用await获取数据 async function useGeoData() { const geoData = await fetchGeoData(); console.log('存入变量的数据:', geoData); // 在这里使用geoData做后续操作 } useGeoData(); // 方式2:用.then获取数据 fetchGeoData().then(geoData => { console.log('存入变量的数据:', geoData); });
关键注意点
- 不要混合
await和.then,避免逻辑混乱和返回值丢失。 - 异步函数调用后返回的是Promise,必须通过
await(仅在async函数内可用)或.then才能拿到实际数据,不能直接赋值给变量。 - 务必检查
response.ok状态,处理HTTP请求失败的情况。 - Geoapify返回的经纬度位于
result.features[0].properties.lat和result.features[0].properties.lon,需根据API返回结构正确提取。
内容的提问来源于stack exchange,提问作者Iria
相关产品推荐
相关产品推荐

