Javascript 运行多个异步函数并等待结果
我正试图为谷歌地图API v3编写一个函数。基本上,我将遍历给定形状的所有多边形点,并通过将每个点传递给PHP函数将数据插入MySQL,将它们添加到数据库中Javascript 运行多个异步函数并等待结果,javascript,google-maps,asynchronous,Javascript,Google Maps,Asynchronous,我正试图为谷歌地图API v3编写一个函数。基本上,我将遍历给定形状的所有多边形点,并通过将每个点传递给PHP函数将数据插入MySQL,将它们添加到数据库中 function saveSite() { // Create an array to hold the individual point saving results var submission_Result = []; var final_result = true;
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
}
}
函数saveSite(){
//创建一个数组以保存各个点的保存结果
风险值提交结果=[];
var最终结果=真;
//获取此形状的常规属性
var shape_ID=selectedShape.ID;
var shape_Name=document.getElementById(“info_Name”).value;
var shape_Description=document.getElementById(“info_Description”).value;
变量shape\u Type=shapesArray[shape\u ID]。类型;
var shape_Points=selectedShape.getPath();
//遍历形状中的所有点并保存它们
对于(变量i=0;i 如果(responseCode==200&&data.length您必须在传递的回调中检查此项下载URL
,例如:
downloadUrl(url, function(data, responseCode) {
//...
if (submission_Result.length === shape_Points.length)
allResultsReady();
});
如果所有结果都在中,则将调用函数allResultsReady
使用循环会阻塞整个浏览器窗口,这绝对不是您想要的。完美,这正是我所需要的,它工作起来很有魅力。异步javascript对我来说还是相当新的,所以仍然习惯于这些怪癖。
downloadUrl(url, function(data, responseCode) {
//...
if (submission_Result.length === shape_Points.length)
allResultsReady();
});