简体   繁体   English

嵌套async.each:“错误:回调已被调用”

[英]Nested async.each: “Error: Callback was already called”

I have having troubles getting my nested async.each work and I am not sure why I'm getting the error: Error: Callback was already called even though I have correctly placed my callbacks. 我在嵌套async.each工作上遇到了麻烦,而且我不确定为什么会收到错误消息: Error: Callback was already called即使我正确放置了回调, 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);
    });
  }
}

Any help would be really appreciated. 任何帮助将非常感激。

If the condition is met you're calling again next(); 如果满足条件,则再次调用next(); after looping through default_shift . 在遍历default_shift

 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.

One easy way to solve it, is adding a flag, and ignore second next if shifts overlap. 一种简单的解决方法是添加一个标志,如果移位重叠,则忽略第二个标志。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM