簡體   English   中英

Express.js(Node.js)上的異步SqLite模塊

[英]Asynchronous SqLite module on Express.js (Node.js)

我正在嘗試向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; } }); }); }); } 

第一個問題的解決方案:

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

          });
        });
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM