Nested async.each: "Error: Callback was already called"

Nested async.each: "Error: Callback was already called"

我在嵌套 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);
    });
  }
}

任何帮助将不胜感激。

如果满足条件,您将在 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();