【发布时间】:2018-04-24 20:50:19
【问题描述】:
我正在尝试向数据库发出同步请求并抛出数据来表达。这是代码
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;
}
});
});
});
}
【问题讨论】:
标签: javascript node.js sqlite express