添加对Google Maps API调用的承诺 [英] Adding a promise to a Google Maps API call
问题描述
我需要从Javascript / jQuery中的函数返回一个数组,但该函数在数组设置之前返回(因为它是一个AJAX调用)。
I need to return an array from a function in Javascript/jQuery but the function is returning before the array has been set (as it is an AJAX call).
我被建议使用一个承诺,但我之前没有使用过这些承诺,到目前为止还没有将它实现到我的代码中。这是我的代码:
I have been advised to use a promise but I have not used these before and have so far been unable to implement this into my code. Here is my code:
mapClass.setLatLng = function(location, clubs) {
document.geoCodeRequestCompleteFlag = 0;
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address' : location}, function(results, status) {
//console.log(results);
if(status === "OK") {
var latLngArray = [];
latLngArray.push(parseFloat(results[0].geometry.location.lat()));
latLngArray.push(parseFloat(results[0].geometry.location.lng()));
var sortedArray = mapClass.calculateDistances(clubs, latLngArray);
return sortedArray;
}
});
}
如你所见,当我返回时,sortedArray变量是空的。有没有人有任何想法如何我可以添加阻止代码,以确保在返回之前设置数组变量?
谢谢
As you can see, the sortedArray variable is empty when I return is. Does anyone have any ideas as to how I could add blocking code into this to ensure the array variables are set before returning? Thanks
推荐答案
您使用promises的方式是创建一个promise,然后从您的方法返回该promise。此承诺具有 .then(successHandler,errorHandler)
等方法,使您可以指定在解析的承诺时执行的函数(给定值)。然后,当您在将来的某个时刻从地理编码器调用中返回结果时,您将解决该承诺。
The way you use promises is that you create a promise and then return that promise from your method. This promise has methods like .then(successHandler, errorHandler)
that enable you to specify functions to execute when the promise is resolved (is given a value). You then resolve the promise when you get back the results from the geocoder call at some point in the future.
In jQuery, the promises are called Deferreds.
您的代码将更改为以下内容:
Your code would then change to something like this:
mapClass.setLatLng = function(location, clubs) {
var deferred = $.Deferred(),
geocoder = new google.maps.Geocoder();
document.geoCodeRequestCompleteFlag = 0;
geocoder.geocode({'address' : location}, function(results, status) {
if (status === 'OK') {
var latLngArray = [
+results[0].geometry.location.lat(),
+results[0].geometry.location.lng()
];
deferred.resolve(mapClass.calculateDistances(clubs, latLngArray));
} else {
deferred.reject(status);
}
});
return deferred.promise();
}
您可以这样使用它:
mapClass.setLatLng('123 Some St, Wherever', [/* clubs */])
.then(function (sortedArray) {
console.log('Promise resolved with: ', sortedArray);
}, function (err) {
console.error('Uh oh! An error occurred!', err);
});
这篇关于添加对Google Maps API调用的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!