我在此項目中使用async庫。一個函數(下面複製)包含一個嵌套循環來構建一個2D數組。在數組完全構建之前調用回調函數。我真的很想了解爲什麼會發生這種情況並瞭解更多最佳實踐。解決這個問題的最好方法是什麼?迭代完成前發生回調觸發
function getStopTimesForTrips(cb) {
timeTable.listOfTripIds.forEach(function(id){
retrieveTimesByTrip(id, function(err, st){
var tempArray = [];
st.forEach(function(st){
tempArray.push(st.arrival_time);
});
timeTable.stopTimes.push(tempArray);
});
});
// cb(null, timeTable); <- This line fires the callback before we finish building the array.
setTimeout(function(){cb(null, timeTable);},2500); // This effective solution is poor form. What's the correct way to solve this issue?
}
你甚至沒有使用庫提供的'async'方法。 – choz
看起來像一個異步函數循環,但是你可以稱之爲回調而不用等待它們全部被調用。 –