我正在尝试向数据库发出同步请求并将数据传递给表达。这是代码
app.get('/', (req, res) => {
let db = new sqlite3.Database('./Problems.db');
let sql = 'SELECT * FROM Problems ORDER BY problem_id';
let data;
db.all(sql, [], (err, rows, res) => {
data = DBFetchingAllData(rows, db);
});
res.render('pages/index', { data });
});
由于db.all()
是异步函数,res.renders
捕获undefined
,这是我的问题之一。第二个问题是在函数DBFetchingAllData
中,我认为它返回rows
,但实际上什么也没返回。如果有人帮助我使 DBFetchingAllData 正确返回行并使 db.all() 同步,我将非常感激。
function DBFetchingAllData(rows, db) {
rows.forEach((row, index) => {
// loop over the problem_questions_id
// Array with answers
row.answer = [];
let row_with_id = _.split(row.problem_questions_id, ',');
row_with_id.forEach((id) => {
let sql = `SELECT * FROM QuestionsAndAnswers WHERE id = ?`;
// use db.all not db.get to fetch an array of answers
// this call is asynchronous so we need to check if we are done inside the callback
db.get(sql, [id], (err, answer) => {
// "answers" is an array here
row.answer.push(answer);
// if the index is one less than the length it's the last
if (index === rows.length-1) {
// we're done!
return rows;
}
});
});
});
}
最佳答案
第一个问题的解决方案:
只需在所有回调函数中调用res.render
即可
app.get('/', (req, res) => {
let db = new sqlite3.Database('./Problems.db');
let sql = 'SELECT * FROM Problems ORDER BY problem_id';
let data;
db.all(sql, [], (err, rows, res) => {
data = DBFetchingAllData(rows, db);
res.render('pages/index', { data });
});
});
第二个解决方案:
您忘记在函数末尾返回 rows
:
function DBFetchingAllData(rows, db) {
return Promise((resolve)=>{
rows.forEach((row, index) => {
// loop over the problem_questions_id
// Array with answers
row.answer = [];
let row_with_id = _.split(row.problem_questions_id, ',');
row_with_id.forEach((id) => {
let sql = `SELECT * FROM QuestionsAndAnswers WHERE id = ?`;
// use db.all not db.get to fetch an array of answers
// this call is asynchronous so we need to check if we are done inside the callback
(function(row,index){
db.get(sql, [id], (err, answer) => {
// "answers" is an array here
row.answer.push(answer);
// if the index is one less than the length it's the last
if (index === rows.length-1) {
// we're done!
resolve(rows)
}
});
})(row,index)
});
});
});
}
关于javascript - Express.js (Node.js) 上的异步 SqLite 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47242865/