以下代码使用q.js来获取学生的详细信息。除了未将获取的类别和城市映射到变量studentdetails
中之外,其他所有内容均正常运行。它仅包含由邮件查询获取的详细信息(名称,电子邮件,id,dob)。我要去哪里错了?任何线索将不胜感激。
//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
最佳答案
您可以尝试这样:
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
});