I am trying to make this function make an appropriate callback. As it is written, the callback will be called twice - once for the synchronous 'if' statement and one for the asynchronous 'test2.save' statement. I am putting the counter code in just as an example that I tried. It doesn't work since the bottom if statement is synchronous. I already know what is wrong with this code, but I have no idea about how to make it better.
var postMatches = function(user1, userResults, callback) {
User.find({}, {username: 1, testResults: 1}, (err, users) => {
var counter = 0;
users.forEach(function(user2){
counter++;
if(user1 !== user2.username && user2.testResults !== undefined) {
var test1 = new Test({
username: user1,
match: user2.username,
compatability: mbti[userResults][user2.testResults],
alreadyMatches: false
});
test1.save( () => {
var test2 = new Test({
username: user2.username,
match: user1,
compatability: mbti[user2.testResults][userResults],
alreadyMatches: false
});
test2.save( () => {
if(counter === users.length) {
callback();
}
});
})
} else {
if(counter === users.length) {
callback();
}
}
})
})
};