简体   繁体   中英

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.

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(); after looping through 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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