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);
});

更多相关文章

  1. 对多维数组中的列进行排序
  2. JS将字符串转换为数组
  3. 将textarea值附加到现有数组javascript
  4. ECMAScript6(6):数组的扩展
  5. 希望日期开始结束在一个数组中的while循环中为一个房间ID
  6. 如何使用客户端Javascript数组并通过节点发布。将js API插入Mong
  7. 在量角器中检索子元素的数组
  8. 从特定条件下存储在localStorage中的数组中删除对象?
  9. Python 3.4:试图让这个模块对这个2d数组中的销售总数求和。不工作

随机推荐

  1. 最近状态不咋好 ...
  2. Java后端开发学习路线「光头强版」发布
  3. 一文学会 Node.js 中的流[每日前端夜话0x
  4. 常用 Linux 发行版操作系统大盘点!
  5. Java中static变量作用和用法详解
  6. 不就看一下Java后端开发书架吗?这有啥不行
  7. 9 个强大的 JavaScript 小技巧[每日前端
  8. 从 JavaScript、ES6、ES7 到 ES10,你学到
  9. 用 globalThis 访问全局对象[每日前端夜
  10. 生产环境下的 Node.js 日志记录方案[每日