我在使用 sequelize js 从数据库中检索数据时遇到问题。我是 NODEJS 的新手。我不知道 Promise 和 Promise.all 是否内置函数所以我也在我的代码中安装并要求 npm promise。下面是我的代码。
var Promise = require('promise');
var user_profile = new Promise(function(resolve, reject) {
db.user_profile.findOne({
where: {
profile_id: new_profile_id
}
}).then(user => {
console.log('Summary Result User found.');
resolve(user);
});
});
var all_reports = new Promise(function(resolve, reject) {
db.report.all().then(reports => {
console.log('Summary Result Reports found.');
resolve(reports);
});
});
var report_details = new Promise(function(resolve, reject) {
db.report_detail.findAll({
where: {
profile_id: new_profile_id
}
}).then(report_details => {
console.log('Summary Result Report Details found');
resolve(report_details);
});
});
var all_promises = Promise.all([user_profile, all_reports, report_details]).then(function(data) {
console.log('**********COMPLETE RESULT****************');
console.log(data);
}).catch(err => {
console.log('**********ERROR RESULT****************');
console.log(err);
});
我想获取所有三个查询的数据。当我单独运行它们时,我得到了数据,但是当我在 Promise.all 中运行它们时,我只得到 user_profile 数据,而其他两个仍未定义 我也尝试用 .then 嵌套这些查询,但结果仍然相同我只得到一个查询数据其他两个未定义
然后链接
var results = [];
var new_profile_id = req.params.profile_id;
console.log(new_profile_id);
db.user_profile.findOne({
where: {
profile_id: new_profile_id
}
}).then(user => {
console.log('Summary Result User found.');
results.push(user.dataValues);
return user;
}).then(user => {
db.report.all().then(reports => {
console.log('Summary Result Reports found.');
results.push(reports.dataValues);
return reports
});
}).then(reports => {
db.report_detail.findAll({
where: {
profile_id: new_profile_id
}
}).then(report_details => {
console.log('Summary Result Report Details found');
results.push(report_details.dataValues);
console.log('**********COMPLETE RESULT****************');
console.log(results);
console.log('**********COMPLETE RESULT****************');
return report_details;
});
});
有人可以在这个概念上帮助我我做错了什么。谢谢