I have this piece of code
User.find({}, function(err, users) {
for (var i = 0; i < users.length; i++) {
pseudocode
Friend.find({
'user': curUser._id
}, function(err, friends) * * ANOTHER CALLBACK * * {
for (var i = 0; i < friends.length; i++) {
pseudocode
}
console.log("HERE I'm CHECKING " + curUser);
if (curUser.websiteaccount != "None") {
request.post({
url: 'blah',
formData: blah
}, function(err, httpResponse, body) { * * ANOTHER CALLBACK * *
pseudocode
sendMail(friendResults, curUser);
});
} else {
pseudocode
sendMail(friendResults, curUser);
}
});
console.log("finished friend");
console.log(friendResults);
sleep.sleep(15);
console.log("finished waiting");
console.log(friendResults);
}
});
A couple of asynchronous things happen here. For each user, I want to find their respective friends and combine them with a variable. Then I want to check if this user has a website account, and if so, make a mail request and get some information there. The only thing is that everything happens out of order, since the code does not wait for the callbacks to complete. I use sleep, but this does not solve the problem either since it is still confused.
I looked at async, but these functions are intertwined and not shared, so I was not sure how it would work with async.
Any suggestions for this code to run sequentially?
Thank!