Ajax GET函数被其他函数调用时无法返回成功值,返回值为空求助
解决控制台输出正确但函数返回值为空的问题
嘿,这个问题我太熟了!核心原因就是Ajax请求是异步的——你的fnWhatThreeWords函数会在Ajax请求完成前就先返回,所以返回值是空;而控制台能输出正确结果,是因为请求成功后,success回调里的代码才会执行,这时候数据已经拿到了。
先拆解下你的问题根源
假设你的fnWhatThreeWords是类似这样写的:
function fnWhatThreeWords(Lat, Long) { let threeWords; // 发起异步Ajax请求 $.ajax({ url: '你的what3words接口地址', type: 'GET', success: function(data) { threeWords = data.words; console.log(threeWords); // 这里控制台能输出正确值 } }); return threeWords; // 这里返回时,Ajax请求还没完成,threeWords还是undefined! }
你看,return threeWords的代码会比success回调先执行,自然拿不到结果。
给你几个可行的解决方案
方案1:用回调函数处理异步结果
修改fnWhatThreeWords,让它接受一个回调函数,在请求成功后调用回调传递结果:
function fnWhatThreeWords(Lat, Long, callback) { $.ajax({ url: '你的what3words接口地址', type: 'GET', success: function(data) { const threeWords = data.words; console.log(threeWords); callback(threeWords); // 请求完成后把结果传给回调 } }); }
然后在调用的时候,传入回调来处理结果(包括你的Leaflet绘图逻辑):
$.each(data.d.results, function (index, item) { fnWhatThreeWords(item.Latitude, item.Longitude, function(whatThreeWords) { // 这里可以直接用whatThreeWords做Leaflet绘图操作 console.log('拿到正确的what3words值:', whatThreeWords); }); });
方案2:用Promise包装异步请求(更现代的写法)
把fnWhatThreeWords改成返回Promise,这样可以用.then()或者async/await来处理结果:
function fnWhatThreeWords(Lat, Long) { return new Promise((resolve, reject) => { $.ajax({ url: '你的what3words接口地址', type: 'GET', success: function(data) { resolve(data.words); // 请求成功时返回结果 }, error: function(err) { reject(err); // 请求失败时返回错误信息 } }); }); }
调用时用async/await(注意要在异步函数里使用):
// 把each的回调改成async函数 $.each(data.d.results, async function (index, item) { try { const whatThreeWords = await fnWhatThreeWords(item.Latitude, item.Longitude); // 这里执行Leaflet绘图逻辑 console.log('拿到正确值:', whatThreeWords); } catch (err) { console.error('请求出错了:', err); } });
或者用.then()链式调用:
$.each(data.d.results, function (index, item) { fnWhatThreeWords(item.Latitude, item.Longitude) .then(whatThreeWords => { // 执行Leaflet绘图逻辑 console.log('拿到正确值:', whatThreeWords); }) .catch(err => { console.error('请求出错了:', err); }); });
总结一下
异步操作的核心是不能同步返回结果,必须等待请求完成后再处理数据。上面的两种方案都是让代码“等待”异步请求完成,再去处理拿到的what3words值,这样就能解决返回值为空的问题啦。
内容的提问来源于stack exchange,提问作者Xeverus
相关产品推荐
相关产品推荐

