2017-11-08 8 views
0

配列のデータをdb.get(...) => {...}から保存しようとしていますが、空の配列を取得するたびにスコープがあるか、メソッドdb.get(...) => {...}であるとわかりません。これを解決するのを手伝ってください。私の主な目標はノードのsqlite3パッケージの結果を保存する

const sqlite3 = require('sqlite3'); 
 

 
let db = new sqlite3.Database('./ProblemsForPatan.db', sqlite3.OPEN_READONLY); 
 

 
let sql = 'SELECT * FROM Problems'; 
 

 
db.all(sql, [], (err, rows) => { 
 

 
    rows.forEach((rowQuestion) => { 
 

 
    let arrayWithQuestionsId = _.split(rowQuestion.problem_questions_id, ',') 
 
    
 
    var arrayOfAnswers = [] 
 
    arrayWithQuestionsId.forEach((id) => { 
 

 
     let sql = `SELECT * FROM QuestionsAndAnswersOfProblems WHERE question_id = ?` 
 
     
 
     db.get(sql, [id], (err, rowAnswer) => { 
 
     console.log(rowAnswer) // Object 
 
     arrayOfAnswers.push(rowAnswer) 
 
     }) // db.get(...) 
 
     console.log(arrayOfAnswers) // [] 
 
    }) // arrayWithQuestionsId.forEach(...) 
 
    rowQuestion.answer = arrayOfAsnwers; 
 
    }) // rows.forEach(...) 
 
    console.log(rows) // [objects with 'answer': []] 
 
}) // db.all(...)

はそれがrowQuestionオブジェクトを取得し、答えをフェッチするdb.get()へのあなたの呼び出しは、あなたのことを意味し、非同期である代わりにrowQuestionanswer: [empty]

答えて

1

answer: [array of objects]フィールドを追加私がしたいのですか答えが入力される前にconsole.log(rows)が実行されています。 「行」の処理が終了したら、コールバックを使用する必要があります。

db.all(sql, [], (err, rows) => { 
    // track the index here with a second parameter of "index" 
    rows.forEach((row, index) => { 
    // loop over the problem_questions_id 
    _.split(row.problem_questions_id, ',').forEach((id) => { 
     let sql = `SELECT * FROM QuestionsAndAnswersOfProblems WHERE question_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.all(sql, [id], (err, answers) => { 
     // "answers" is an array here 
     row.answer = answers; 
     // if the index is one less than the length it's the last 
     if (index === rows.length-1) { 
      // we're done! 
      done(rows); 
     } 
     }); 
    }); 
    }); 
}); 

// this is called asynchronously when all the answers have been fetched 
function done(rows) { 
    console.log(rows); 
} 
関連する問題