添加对Google Maps API调用的承诺

我需要从Javascript / jQuery中的函数返回一个数组,但该函数在数组设置之前返回(因为它是一个AJAX调用)。

我被建议使用一个承诺,但我之前没有使用过这些承诺,到目前为止我还没有将它实现到我的代码中。 这是我的代码:

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变量为空。 有没有人有任何想法如何我可以添加阻止代码,以确保在返回之前设置数组变量? 谢谢

您使用promises的方式是创建一个promise,然后从您的方法返回该promise。 这个promise有像.then(successHandler, errorHandler)这样的方法.then(successHandler, errorHandler)它们允许你指定在解析 promise时执行的函数(给定一个值)。 然后,当您在将来的某个时间点从地理编码器调用返回结果时,您将解决该承诺。

在jQuery中,承诺称为Deferreds 。

然后您的代码将更改为以下内容:

 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官方NPM模块 ,则可以更轻松,更清洁。

首先,您需要使用Promise属性初始化客户端:

 const googleMapsClient = require('@google/maps').createClient({ key: 'your API key here', Promise: Promise }); 

然后,你需要做的就是使用asPromised() ,然后你就可以了:

 googleMapsClient.geocode({ address: '1600 Amphitheatre Parkway, Mountain View, CA' }) .asPromise() .then(response => response.json.results) .catch(err => console.log(err))