Chetan Gawai Chetan Gawai - 3 months ago 10
MySQL Question

Issue while using q.js promises

The following code used q.js to fetch details of students. Everything works properly except that the fetched categories and city are not mapped in variable

studentdetails
. It only contains the details(name,email,id,dob) fetched by the mail query. Where am I going wrong? Any leads will be highly appreciated.

//fetches category of student
var getJobCategories = function(student) {
var deferred = Q.defer();
var categoryquery = 'select c.name,c.id from category c,student_category sc where xxxx';
db.query(categoryquery, function(err, categories, fields) {
if(categories.length == 0) {
student.categories = "NA";
} else {
student.categories = categories;
}
console.log(student)//prints details with categories
deferred.resolve();
});
return deferred.promise;

}
//fetches city of student
var getCurrentCity = function(student) {
var deferred = Q.defer();
var cityquery = 'select l.name,l.id from location l ,student_location sl where xxxx';
db.query(cityquery, function(err, city) {
if(city.length == 0) {
student.currentcity = "NA";
} else {
student.currentcity = city;
}
console.log(student)//prints details with city
deferred.resolve();
});
return deferred.promise;

}

var query='select name,email,id,dob from student limit 1,10';
db.query(query, function(err1, studentdetails) {
var promise1=studentdetails.map(function(student){
var result=getJobCategories(student)

});
var promise2=studentdetails.map(function(student){
getCurrentCity(student)
});

var allpromises= Q.all([
promise1,promise2

]);

Q.allSettled(allpromises)
.then(function (results) {
next(null,{
result: studentdetails,
msg: "Fetched successfully"
});
});//then
});//query

Answer

You may try this :

db.query(query, function(err1, studentdetails) {
             var allStudentJobCategories = 
                studentdetails.map(function(student){ 
                    return getJobCategories(student)
                });

             var allStudentCities = 
                 studentdetails.map(function(student){ 
                   return getCurrentCity(student)
                 });

             var allpromises= Q.all([
                 Q.all(allStudentJobCategories), Q.all(allStudentCities)
             ]);

             Q.allSettled(allpromises)
              .then(function (results) {
                       next(null,{
                     result: studentdetails,
                     msg: "Fetched successfully"
                 });     
             });//then
    });