这是我的(简单)问题:
我有一个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满了,假的在返回trueonStepChanging
事件,以确定我们是否能够进入下一步骤(地址即可),而不是(地址是错的)
我正在使用这个SO问题来更好地理解Deferred
,但我无法成功。
有人可以帮助我吗?
非常感谢
好的,正如@Bergi所说,使用此插件似乎无法实现。
因此,我绕过了这个问题,将Next
按钮替换为伪造的按钮,该伪造按钮调用了异步事件。在此事件结束时,如果结果正常,我将Next
按钮替换为我克隆的原始按钮,并触发该按钮上的一个click
事件以传递到下一步,而无需用户单击两次。
不知道它是否真的很干净,但是可以满足我的需求
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句