2017-11-08 7 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 개체를 얻을로 대신 rowQuestion answer: [array of objects] 필드를 추가의 answer: [empty]

답변

1
답변을 가져올 db.get()에 대한 귀하의 호출이 있음을 의미하는 비동기

당신의 응답이 채워지기 전에 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); 
}