这里是我的(简单)的问题:在JS函数中等待异步调用的结束。 (?jQuery.Deferred)
我有一个JavaScript函数,以便得到一些结果异步调用外部API。我需要等待这些结果,因为我想对它们进行一些测试以确定它们是否有效,但Deferred
对我来说非常复杂,我无法成功。
这里是我做了什么:
$("#step-content").steps({
//some parameters
onStepChanging: function(event, currentIndex, newIndex) {
verifyAddress().done(function(test) {
if($("#hdnLatitude").val() == "" || $("#hdnLongitude").val() == "")
test = false;
else
test = true;
console.log(test); // test is true or false, that's good
return test;
});
console.log(test); // test is always empty here
//Here, I just need to do return true or return false to block step-changing if there is an error.
return test;
}
});
基本上,这里是我的verifyAddress
功能:
function verifyAddress() {
var r = $.Deferred();
var geocoder = new google.maps.Geocoder();
if (geocoder) {
var adressToGeocode = /* Get the address to geocode */
geocoder.geocode({ 'address': adressToGeocode }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
//Save the lat/lng returned in #hdnLatitude and #hdnLongitude
}
r.resolve();
});
}
//Not sure where to place the return r ; try elsewhere but no success
return r;
}
所以我需要的是等待verifyAdress()
结束并获得# hdnLatitude和#hdnLongitude已填充,并在onStepChanging
事件中返回false为false,以确定是否可以转到下一步(地址是OK)而不是(add雷斯是错误的)
我使用this SO question以更好地了解Deferred
,但我无法成功。
有人能帮我吗?
非常感谢
如何从异步函数返回。经典。看看[这里](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call)了解为什么你不能这样做。 – dfsq 2014-09-20 14:04:46
嗨。我知道对于像我这样的初学者来说这是一个经典问题,但我真的需要帮助来理解问题。我看过这个链接,是否必须将回调传递给我的'verifyAddress()'方法?我无法理解底层逻辑... – AlexB 2014-09-20 14:09:32
如果可能,可以发布'html',“调用Google服务器”部分?谢谢 – guest271314 2014-09-20 14:32:05