Frederic Bastiat
Frederic Bastiat

Reputation: 693

Incrementing not working

I'm having trouble getting numNotes to increment. Everything else seems to work just fine.

function getNotes(done) {
  noteSchema.find({}).exec((err, notes) => {
    var numNotes = 0;
    async.each(notes, (n, next) => {
        userSchema.findById(n.userId, (err, user) => {
        if (err || !user) { next(); return; }
        var emailsStr = utils.getEmailsString(user.emails);
            if (!utils.toSkipEmail(emailsStr)) {
                meetingSchema.findById(n.meetingId, function (err, meeting) {
                    if (meeting.name.displayValue.indexOf('test', 'Test') == -1) {
                        numNotes++;
                    }
                });
            }
            next();
        })
    }, (err, result) => {
      console.log(util.format('Total Number of Notes: %d', numNotes));
      done(null);
    });
  });
}

Upvotes: 1

Views: 58

Answers (1)

Thomas Wolfe
Thomas Wolfe

Reputation: 638

I think that your next() might be getting invoked before numNotes++ is ever run. This is because Node.JS is non-blocking and doesn't run your code sequentially if there are async functions present.

To see the previous in action place a console.log('test 1') after if(!utils.toSkipEmail(emailsStr)), a console.log('test 2') after the if (meeting.name.displayValue.indexOf('test', 'Test') == -1){...} block, and also a console.log('test3') after the if(!utils.toSkipEmail(emailsStr)){...} block.

In order to fix your issue try the following:

if (!utils.toSkipEmail(emailsStr)) {

  meetingSchema.findById(n.meetingId, function(err, meeting) {
    if (meeting.name.displayValue.indexOf('test', 'Test') == -1) {
      numNotes++;
    }
    next();
  });
} else {
  next();
}

Upvotes: 2

Related Questions