I have this chunk 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);
}
});
There's a couple asynchronous things happening here. For each user, I want to find their relevant friends and concat them to a variable. I then want to check if that user has a website account, and if so, make a post request and grab some information there. Only thing is, that everything is happening out of order since the code isn't waiting for the callbacks to finish. I've been using a sleep but that doesn't solve the problem either since it's still jumbled.
I've looked into async, but these functions are intertwined and not really separate, so I wasn't sure how it'd work with async either.
Any suggestions to get this code to run sequentially?
Thanks!
Aucun commentaire:
Enregistrer un commentaire