0
我正在嘗試爲Google Maps API v3編寫一個函數。基本上,我循環遍歷給定形狀的所有多邊形點,並通過將每個點傳遞給將數據插入MySQL的PHP函數將它們添加到數據庫中。運行多個異步函數並等待結果
function saveSite() {
// Create an array to hold the individual point saving results
var submission_Result = [];
var final_result = true;
// Get the general properties for this shape
var shape_ID = selectedShape.ID;
var shape_Name = document.getElementById("info_name").value;
var shape_Description = document.getElementById("info_description").value;
var shape_Type = shapesArray[shape_ID].type;
var shape_Points = selectedShape.getPath();
// Run through all points in the shape and save them
for (var i = 0; i < shape_Points.length; i++) {
var curPoint = shape_Points.getAt(i);
// Prepare the point data to be saved
var url = pageDir + "phpsqlinfo_addShapeData.php?db=" + database + "&job=" + jobnumber +
"&stype=" + shape_Type + "&snumber=" + shape_ID + "&sname=" + encodeURIComponent(shape_Name) +
"&sdesc=" + encodeURIComponent(shape_Description) + "&sseqno=" + i + "&slat=" + curPoint.lat() + "&slng=" + curPoint.lng();
// Attempt to save the shape data
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length <= 1) {
submission_Result.push(true);
} else {
submission_Result.push(false);
}
});
}
// Run through all point results and confirm correct submission of points
for (var i = 0; i < submission_Result.length; i++) {
if (submission_Result[i] == false) {
final_result = false;
}
}
// If all points were successfully saved, tell the user
if (final_result == true) {
// All points saved successfully so do something
} else {
// Something went wrong and not all points were added so do something else
}
}
我知道* downloadURL *運行作爲異步函數,因此我目前無法通過的* submission_result *陣列循環,並檢查是否正確添加了所有點。 我的問題是,有沒有什麼辦法可以等待所有的異步調用完成,然後檢查結果數組?
也許這樣的事情,例如?:
});
}
while (submission_Result.length < shape_Points.length) {
// Do something wait a short while
};
// Run through all point results and confirm correct submission of points
for (var i = 0; i < submission_Result.length; i++) {
任何想法,將不勝感激爲我完全難倒!
在此先感謝。
完美,這就是我所需要的,它就像一個魅力。異步JavaScript對我來說還是比較新的,所以還是習慣了這些怪癖。 – JohnHenry 2012-02-23 09:16:24