這裏是我的(簡單)的問題:在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