[英]how to return value to parent function from nested anonymous function
I have a javascript function which should return a geocoding for a string: 我有一个javascript函数,它应该返回一个字符串的地理编码:
function codeAddress(address) {
var result = (new google.maps.Geocoder()).geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
return String(results[0].geometry.location.Ya)+','+String(results[0].geometry.location.Za)
} else {
return status;
}
});
console.log(result);
return result
}
However it returns "undefined". 但是它返回“未定义”。 I understand the bug here,ie, since javascript is asynchronous, its returning from the function codeAddress
even before function(results, status)
gets fully executed. 我理解这里的错误,即,因为javascript是异步的,它甚至在function(results, status)
完全执行之前从函数codeAddress
返回。 But I need to know whats the solution here and the best practice. 但我需要知道这里的解决方案和最佳实践。
Since it's asynchronous, you should pass a callback which handles the function: 由于它是异步的,你应该传递一个处理函数的回调:
function codeAddress(address, callback) {
(new google.maps.Geocoder()).geocode({
'address' : address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback(String(results[0].geometry.location.Ya) + ','
+ String(results[0].geometry.location.Za))
} else {
callback(status);
}
});
}
codeAddress("test", function(result) {
// do stuff with result
});
If you're using jQuery, you could also use deferred: 如果你正在使用jQuery,你也可以使用deferred:
function codeAddress(address, callback) {
var dfd = new jQuery.Deferred();
(new google.maps.Geocoder()).geocode({
'address' : address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// trigger success
dfd.resolve(String(results[0].geometry.location.Ya) + ','
+ String(results[0].geometry.location.Za));
} else {
// trigger failure
dfd.reject(status);
}
});
return dfd;
}
codeAddress("some address").then(
// success
function(result) {
// do stuff with result
},
// failure
function(statusCode) {
// handle failure
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.