有人可以告诉我为什么当console.log返回正确答案时我的返回值是空白吗?
我有一个函数可以对一系列结果进行交互,并且我正在尝试显示我传递到该变量中的十进制度坐标的三词地址名称。
$.each(data.d.results, function (index, item) {
var whatThreeWords = fnWhatThreeWords(item.Latitude,item.Longitude);
//other code here to plot via leaflet
});
我的 fnWhatThreeWords 看起来像:
function fnWhatThreeWords(Lat,Lng) {
var whatThreeWords = "";
$.ajax({
type: "GET",
dataType: "json",
url: "https://api.what3words.com/v2/reverse?coords="+Lat+","+Lng+"&key=APIKEY&lang=en&format=json",
error: function (err) {
console.log(err);
},
success: function (data, status, xhr) {
console.log(data.words);
whatThreeWords = data.words;
}
});
return whatThreeWords;
}
console.log 返回适当的响应:“crumples.harmless.measuring”,但是当我返回whatThreeWords 全局函数变量时,结果为空;
var point = new L.marker([item.Latitude, item.Longitude], {icon: color}).bindPopup("<b>Residence "+Edit+"</b><br>RPA Id: "+item.RPAId+"<br>"+item.Address+"<br>what3words: "+whatThreeWords, {autoClose:false});
最佳答案
要在 ajax 请求之外操作 whatThreeWords
变量,您可以为 $.ajax()
设置额外的参数 async
。但这实际上是防止 js 中异步代码的一个不好的做法。
我的建议是在分配给 success 属性的回调中处理结果。这才是正确的做法。
为了避免回调,以防您要在其他异步内容中创建更多异步内容,请使用 Promises 来组织代码并使其更具可读性,因为它看起来像同步的。
关于javascript - ajax GET 函数在被另一个函数调用时不返回成功值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49494792/