Express.js上的异步SqLite模块(Node.js)

时间:2017-11-11 21:17:11

标签: javascript node.js sqlite express

我尝试向db发出同步请求并将数据抛出来表达。这里的代码



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;
        }
      });
    });
  });
}




1 个答案:

答案 0 :(得分:1)

第一个问题的解决方案:

只需在所有回调函数中调用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)
            });

          });
        });
    }