[英]How to get the result from an anonymous function in Javascript?
我正在使用一個簡單的腳本對地址進行地址解析。
var geocoder;
var departure;
var arrival;
function initialize() {
geocoder = new google.maps.Geocoder();
}
google.maps.event.addDomListener(window, 'load', initialize);
function geocode(options) {
var address = options.address.val() || null;
var result = {};
if (address) {
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
result.lat = results[0].geometry.location.lat();
result.lng = results[0].geometry.location.lng();
} else {
result.lat = null;
result.lng = null;
}
});
}
}
function geocode_all() {
departure = geocode({
address: $('#departure')
});
//console.log(departure);
arrival = geocode({
address: $('#arrival')
});
//console.log(arrival);
}
我希望我的離開變量和到達變量成為具有最終經度和緯度的對象。
由於結果變量超出范圍,我應該如何進行?
謝謝 !
問題不在於該函數是匿名的,也不是作用域。 問題是Google地理位置API是異步的 。 您的geocode
函數不可能返回其結果; 取而代之的是,就像Google的函數一樣,它必須接受一個回調,然后在知道結果后再返回結果。 (或者它可以通過“承諾”模式間接使用回調,但是基本概念是相同的。)
因此,使用回調:
function geocode(options, callback) {
// ^--- Accept the callback
var address = options.address.val() || null;
var result = {};
if (address) {
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
result.lat = results[0].geometry.location.lat();
result.lng = results[0].geometry.location.lng();
} else {
result.lat = null;
result.lng = null;
}
callback(result); // <== Call it
});
}
}
// usage
geocode({/*...*/}, function(result) {
// This gets called later, asynchronously, with the result
});
或使用jQuery Deferred
/ Promise
:
function geocode(options) {
var d = new $.Deferred(); // <== Create the deferred
var address = options.address.val() || null;
var result = {};
if (address) {
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
result.lat = results[0].geometry.location.lat();
result.lng = results[0].geometry.location.lng();
} else {
result.lat = null;
result.lng = null;
}
// Resolve the Deferred using your result
d.resolve(result);
});
}
// Return the Promise for the Deferred
return d.promise();
}
// Usage
geocode({/*....*/}).done(function(result) {
// This gets called later, asynchronously, with the result
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.