【问题标题】:Nested async.each: "Error: Callback was already called"嵌套 async.each:“错误:回调已被调用”
【发布时间】:2017-06-23 12:19:43
【问题描述】:

我无法让嵌套的async.each 工作,我不确定为什么会收到错误:Error: Callback was already called,即使我已正确放置回调。

checkDefaultOverlap: function(default_shifts, done) {
    async.each(default_shifts, function(default_shift, next) {
        var subarray = default_shifts.slice(default_shifts.indexOf(default_shift) + 1, default_shifts.length - 1);
        async.each(subarray, function(default_shift2, next) {
            default_shift.week_days.map(function(day1) {
                default_shift2.week_days.map(function(day2) {
                    if (day1 === day2 &&
                         default_shift.start <= default_shift2.end && default_shift2.start <= default_shift.end)
                        next({error: 'The shifts overlap!'});
                });
            });
            next();
        }, function(err) {
            if (err) next(err);
            else next(null);
        });
    }, function(err) {
        if (err) return done(err);
        else return done(null);
    });
  }
}

任何帮助将不胜感激。

【问题讨论】:

  • 哇,你是回调地狱,请重构你的代码,让它更易读
  • 作为第一步,您可以删除内部 async.each() 并将其替换为循环或循环的声明性版本。

标签: javascript node.js each async.js


【解决方案1】:

如果满足条件,您将在循环完default_shift 后再次调用next();

 default_shift.week_days.map(function(day1) {
            default_shift2.week_days.map(function(day2) {
                if (condition)
                    next({error: 'The shifts overlap!'}); //The problem is here.
            });
});
next(); //If shifts overlap, next was already called.

解决它的一个简单方法是添加一个标志,如果班次重叠则忽略第二个。

var nextCalled = false;
default_shift.week_days.map(function(day1) {
    default_shift2.week_days.map(function(day2) {
        if (condition && !nextCalled){
            next({error: 'The shifts overlap!'});
            nextCalled = true;
        }
    });
});

if(!nextCalled)
   next();

【讨论】:

  • 该标志是我真正需要的代码才能工作。太感谢了! :)
猜你喜欢
  • 2016-01-26
  • 2016-11-22
  • 1970-01-01
  • 1970-01-01
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
  • 2015-08-13
  • 1970-01-01
相关资源
最近更新 更多