How can we implement synchronized code for following code snippet. We are to write code in call-back function of previous function. Which created callback-hell (as they said). How can we write separately males and females record fetching separately which can execute synchronously. How can we retain the value for console.log(id[0]); in for loop. Please correct me if I am in wrong direction.
var male_arr = []; var female_arr = [];
/************* Fetching record from database with condition gender=0
***************/ user.find({gender: 0}, {_id: 1}, function (err_male, male) {
if (err_male) {
console.log(err_male);
}
male_arr = male; // initializing males array
looplength = male.length;
//
// With CAALBACK function, we have fetched records with condition gender = 1
//
user.find({gender: 1}, {_id: 1}, function (err_female, female) {
if (err_female) {
console.log(err_female);
}
female_arr = female; // initializing females array
// Populate the male array
for (var loop = 0; loop < looplength; loop++) {
var id = male_arr.splice(0, 1);
//#1 /*****here is the spliced element********/
console.log("Outside request api");
console.log(id[0]);
// Get all records of females which are in request table of male at id[0]
request.find({male: id[0]._id}, {female: 1}, function (err, data) {
//#2 /*****This value of male in id[0] is not retained for match ********/
console.log("Inside request api");
console.log(id[0]);
if (err) {
console.log(err);
}
});
}
}); });