如何从嵌套匿名函数向父函数返回值 [英] how to return value to parent function from nested anonymous function
本文介绍了如何从嵌套匿名函数向父函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 javascript 函数,它应该返回一个字符串的地理编码:
I have a javascript function which should return a geocoding for a string:
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
}
但是它返回未定义".我理解这里的错误,即,由于 javascript 是异步的,它甚至在 function(results, status)
完全执行之前就从函数 codeAddress
返回.但我需要知道这里的解决方案是什么以及最佳实践.
However it returns "undefined". I understand the bug here,i.e, since javascript is asynchronous, its returning from the function codeAddress
even before function(results, status)
gets fully executed. 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
});
如果你使用 jQuery,你也可以使用延迟:
If you're using jQuery, you could also use 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
}
);
这篇关于如何从嵌套匿名函数向父函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文