在迭代完成之前,回调会触发
16lz
2021-01-22
I'm using the async library in this project. One function (copied below) includes a nested loop to build a 2D Array. The callback is called before the array is completely built. I'd really like to understand why this is happening and learn more about best practices. What is the best way to solve this problem?
我在这个项目中使用异步库。一个函数(下面复制)包括用于构建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?
}
2 个解决方案
#1
1
You don't seem to be using any function from the async
library. The correct solution is to use async
:
您似乎没有使用异步库中的任何函数。正确的解决方案是使用async:
async.each(timeTable.listOfTripIds,function(id,cb2){
retrieveTimesByTrip(id, function(err, st){
var tempArray = [];
st.forEach(function(st){
tempArray.push(st.arrival_time);
});
timeTable.stopTimes.push(tempArray);
cb2(err); // Need to call this to tell async this iteration
// is done. Think of it as an async "return".
});
},function(err){
// if we're here it means the `async.each` is done:
cb(null, timeTable);
});
更多相关文章
- 对多维数组中的列进行排序
- JS将字符串转换为数组
- 将textarea值附加到现有数组javascript
- ECMAScript6(6):数组的扩展
- 希望日期开始结束在一个数组中的while循环中为一个房间ID
- 如何使用客户端Javascript数组并通过节点发布。将js API插入Mong
- 在量角器中检索子元素的数组
- 从特定条件下存储在localStorage中的数组中删除对象?
- Python 3.4:试图让这个模块对这个2d数组中的销售总数求和。不工作