我在嘗試在JavaScript中執行異步函數時遇到了一些問題。基本上我有一個pointArr來存儲路線上的座標。然後我得到了一個moveNext(),它沿着路線獲取每個座標並繪製到地圖上。然後在moveNext()中,我得到另一個數組,它是busList。如果沿着路線的座標與busList的座標相匹配,那麼我將totalBusStopLeft減1。這裏就是我所說的MOVENEXT()的代碼:JavaScript異步循環不返回結果
getAllBusLoc(function(busList) {
//At first I set the totalBusLeft by the length of busList which is 13 in this case
var totalBusLoc = busList.length;
document.getElementById("busStopLeft").innerHTML = totalBusLoc;
timeout = 1500;
pointArr.forEach(function(coord,index){
setTimeout(function(){
moveNext(coord.x, coord.y, index, busList, totalBusLoc);
}, timeout * index);
});
});
function moveNext(coordx, coordy, k, busList, totalBusLoc){
//pointToCompare is the coordinates in the route but not the coordinates of busList
var pointToCompare = coordx + "," + coordy;
//If the coordinates in route matches the coordinate in busList, I minus busLeft by one
if(busList.indexOf(pointToCompare) > -1){
parseFloat(totalBusLoc--);
document.getElementById("busStopLeft").innerHTML = totalBusLoc ;
}
//Code to Add marker
}
然而,與此代碼,我的HTML組件busStopLeft一直顯示13,它是原始totalBusLoc。我想知道我怎麼能從moveNext()中返回被使用的totalBusLoc。有任何想法嗎?
我試過使用async.eachSeries,但是當我導入async.js時,它給了我另一個與dojo崩潰的錯誤消息。 在此先感謝。
這裏就是我試圖用回調部分:
totalBusLoc = busList.length;
document.getElementById("busStopLeft").innerHTML = totalBusLoc;
timeout = 1500;
pointArr.forEach(function(coord,index){
setTimeout(function(busLeft){
moveNext(coord.x, coord.y, index, busList, totalBusLoc);
}, timeout * index);
});
});
function moveNext(coordx, coordy, k, busList, totalBusLoc, callback){
var pointToCompare = coordx + "," + coordy;
if(busList.indexOf(pointToCompare) > -1){
parseFloat(totalBusLoc--);
document.getElementById("busStopLeft").innerHTML = totalBusLoc;
callback(totalBusLoc);
}
}
第二個在moveNext你調用回調但沒有通過回調這就是爲什麼它崩潰 –
@MukeshAgarwal那麼你有什麼想法如何解決這個問題? – hyperfkcb
在'moveNext()'內,只更新局部變量(參數)'totalBusLoc',一個變量在函數結束時消失。您需要刪除該參數,而是將其定義爲包含範圍中的變量,以便在調用moveNext()'之間保留其值。或者閱讀並解析'。來自''busStopLeft''元素的innerHTML'值,並且*表示*。 (順便說一下,在這一行中調用'parseFloat()':'parseFloat(totalBusLoc - );'因爲不使用返回值,所以不會執行任何操作。) – nnnnnn