【问题标题】:What's the best way to loop inside a loop in NodeJS and Mocha?在 NodeJS 和 Mocha 中循环内循环的最佳方式是什么?
【发布时间】:2013-11-26 22:35:08
【问题描述】:

我正在尝试在 NodeJS 中的循环内编写一个循环,但我有点困惑,结果并没有给我预期的结果——有时回调会被命中两次,依此类推。我正在使用异步模块,如果有人能告诉我在下面的代码中哪里可能出错,那就太好了。如果有更好的方法可以做到这一点,我会很感激任何提示。

it("should add some numbers", function(done){
    var typed_totals = 0, i = 0;
    async.each(arr1, function(value, callback1){
        var j = 0;
        async.each(arr2, function(element, callback2){
            testFunction(function(result){
                calculate(result, function(total){
                    typed_totals += total;
                    if(++j < arr2.length){
                        callback2();
                    } else if (++i <= arr1.length){
                        callback1();
                    } else {
                        done();
                    }
                });
            });
        });
    });
});

testFunction() 在我的情况下执行http 请求并获取一些值。 calculate() 实际上只是将其中一些加在一起。

如果有任何不清楚的地方,请发表评论,我会根据需要编辑我的问题。

【问题讨论】:

  • 什么是arr1,什么是arr2,什么是testFunction,什么是calculate,什么是loop,你希望代码做什么?两个循环真的是异步的吗?
  • 顺便说一句,您永远不会调用callback1,因此无论内部混乱中发生了什么,您都永远不会将arr1[0] 作为value 传递给第一个async.each 的迭代器函数(尽管你可能会调用最外层的回调,done。你甚至可能多次调用它,这取决于内部代码的作用。通常你会等待调用最外层的回调,直到最外层的 async.each 的完成回调执行。但是你不要为 async.each 调用定义完成回调。)
  • @Plato 我的错误更新答案。

标签: javascript node.js asynchronous callback mocha.js


【解决方案1】:

我要去睡觉了,如果你用更详细的信息进行编辑,我明天可能会提供更具体的答案,这是我的嵌套 async.each 循环的示例。

var async = require('async');

function addNumbers(arr1, arr2, callback){
  var typed_totals = 0;

  async.each(arr1, iterator1, function(err){
    callback(err, typed_totals);
  });

  function iterator1(val1, done1){
    typed_totals += val1;

    async.each(arr2, iterator2, function(err){
      if(err){ return done1(err) };
      done1(null);
    });

    function iterator2(val2, done2){
      process.nextTick(function(){
        typed_totals += val2;
        done2(null);
      });
    };
  };
};

addNumbers([1,2],[3,4], function(err, total){
  console.log(err, total);
});

【讨论】:

    猜你喜欢
    • 2014-02-18
    • 2018-08-29
    • 2011-10-01
    • 2010-09-14
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    相关资源
    最近更新 更多