2016-10-25 6 views
1

안녕하세요. MySQL 데이터베이스의 데이터를 사용하여 PDF 파일을 작성하려고하지만 스크립트를 실행하면 PDF 파일 작성을 끝내고 그 후에 삽입을 시도합니다. 그것에 대한 데이터 ..... 나는 그것이 노드의 MySQL이 비동기이기 때문에 그것이라고 생각한다. 이것에 대한 해결책이 있습니까? 여기 은 내 코드입니다 ...pdf를 만들 때 노드의 동기식 mysql 쿼리

답변

0

이는 Node.js의 비동기 특성 때문입니다. 몇 가지 영역에서 코드를 신속하게 변경하여 문제를 해결할 수 있습니다. conn.release()pdf.end()과 같은 전화가 인 경우 콜백 번호 외부에 있습니다.

아래 코드에서 conn.release()pdf.end()을 mysql 연결 콜백의 마지막 줄로 이동했습니다.

var project_ID = 1; 
var PDFDocument = require('pdfkit'); 
$('#pdf').click(function(e) { 
    e.preventDefault(); 
    var pdf = new PDFDocument; 
    pdf.pipe(fs.createWriteStream(__dirname + '/../MyFile.pdf')); 
    var option; 
    switch ($("input[name=report-type]:checked").val()) { 
     case 'all-issues': 
      option = {project_id: project_ID}; 
      break; 

     case 'all-issues-customer': 
      option = {project_id: project_ID, customer: customer}; 
      break; 
    } 
    connection.getConnection(function (err, conn) { //make connection to DB 
     if (err) { //error handling 
      showNotification('error connecting: ' + err.stack, 'danger', 'glyphicon glyphicon-tasks'); 
      return; 
     } 
     conn.query('SELECT issues.id, issues.dbid , issues.date, issues.charm , issues.defect ,issues.key , issues.status, issues.summary, issues.description , actions.date as action_date, actions.description as action_desc FROM issues' + 
      ' INNER JOIN actions on issues.id = actions.issue_id WHERE ? ', [option], function (error, data) { 
      if (error) { 
       showNotification('Error :' + error, 'danger', 'glyphicon glyphicon-tasks'); 
      } else { 
       var lastID = -1; 
       data.forEach(function (data) { 
        if (lastID !== data.id) { 
         lastID = data.id; 
         pdf.addPage(); 
         pdf.text('Number :' + data.dbid).moveDown(); 
         pdf.text('Customers :   '); 
         pdf.text('Baseline :   '); 
         pdf.text('Error/Wish :   ' + data.key).moveDown(); 
         pdf.text('Charm : ' + data.charm + '/Defect : ' + data.defect + '     Status : ' + data.status); 
         pdf.text('Summary :    ' + data.summary); 
         pdf.text('Description :   ' + data.description).moveDown(); 
         pdf.text('Actions/ History :').moveDown(); 
        } 
        pdf.text('   - date  : ' + convertDate(data.date)); 
        pdf.text('   description : ' + data.description).moveDown(); 
       }) 
      } 
      conn.release(); 
      pdf.end(); 
     }); 
    }); 
}); 

콜백 논리가 완료 될 때까지 이러한 호출이 이루어지지 않아야합니다. 참고 콜백 내에서 콜백 (또는 그 이상)이있는 경우 해당 콜백 내부에서 해당 함수가 호출되도록해야합니다. Callback Hell의 중간에 자주 나옵니다.

행운을 빕니다!

+1

감사 인사 ..... 나는 pdf.end()를 안쪽으로 옮겨서 작동했습니다. –

+0

당신은 환영합니다 :) – Ding

관련 문제