axios异步请求执行晚于后续代码,赋值变量为undefined如何解决
问题成因
该问题属于典型的JavaScript异步执行问题,核心原因如下:
axios.get是异步网络请求,发起后不会阻塞后续同步代码执行,JS引擎会先跑完所有同步任务,再处理异步请求返回后的回调逻辑- 你的
findLatLng函数没有显式返回值,默认返回undefined,所以执行latlng = findLatLng()时,拿到的就是undefined,后续同步执行的console.log(latlng)自然打印undefined then回调里的return语句属于回调函数的返回值,并不会作为findLatLng的返回值向外传递。等网络请求完成、then回调执行时,同步代码早就跑完了,所以你会看到then里的打印晚于外部的latlng打印。后续手动查看latlng时,请求已经完成,值已经被更新,所以能看到正确结果。
修复方案
方案1:使用async/await(最推荐)
首先让findLatLng返回axios请求的Promise实例,外部用async/await等待异步结果返回后再执行后续逻辑:
var latlng = {lat: 7, lng: 7}; function findLatLng() { var testLocation = '350 Victoria St, Toronto'; // 这里返回axios的Promise实例 return axios.get('https://maps.googleapis.com/maps/api/geocode/json', { params: { address: testLocation, key: 'MY KEY', } }) .then(function(response) { console.log(response.data.results[0].geometry.location); return response.data.results[0].geometry.location; }) .catch(function(error) { console.log(error); }); } // 用async函数包裹异步逻辑 async function init() { latlng = await findLatLng(); console.log(latlng); // 后续所有依赖latlng的逻辑都放在这里执行 } init();
方案2:在then回调中处理后续逻辑
直接把依赖latlng的操作放到请求成功的回调里执行:
var latlng = {lat: 7, lng: 7}; function findLatLng() { var testLocation = '350 Victoria St, Toronto'; axios.get('https://maps.googleapis.com/maps/api/geocode/json', { params: { address: testLocation, key: 'MY KEY', } }) .then(function(response) { const location = response.data.results[0].geometry.location; console.log(location); // 赋值和后续逻辑都在这里处理 latlng = location; console.log(latlng); // 其他依赖latlng的逻辑写在这里 }) .catch(function(error) { console.log(error); }); } findLatLng();
内容的提问来源于stack exchange,提问作者user14437282
相关产品推荐
相关产品推荐

