Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to fill an array outside the function clause in nodejs

I want to fill an array outside the function block

app.get('/getpackages/:dateStart/:dateEnd/:limit', function (req, res) {
  var xlsSourceFilesRetrievedTsdz = []
  var xlsSourceFilesRetrievedSvn = []

  var dateStart = req.params.dateStart;
  var dateEnd = req.params.dateStart;
  var limit = Number(req.params.limit);
  
  let sql = 'SELECT * FROM summary_dz WHERE Start != "" AND  Start BETWEEN ? AND ? LIMIT ?'
  db.query(sql, [dateStart,dateEnd,limit], function (err, results) {
    if (err) throw err;
    for (const counter in results) {  
      xlsSourceFilesRetrievedTsdz.push(results[counter].XlsSourceFile);
    }
    // console.log(xlsSourceFilesRetrievedTsdz)
  });
  console.log(xlsSourceFilesRetrievedTsdz)

I want to fill xlsSourceFilesRetrievedTsdz. Whats wrong with what i wrote? I get an emty array. The console.log inside the block in comment gives the wanted result How can the from outside the block?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Doing this should works:

app.get('/getpackages/:dateStart/:dateEnd/:limit', async (req, res) => {
  var xlsSourceFilesRetrievedTsdz = []
  var xlsSourceFilesRetrievedSvn = []
  const promiseQuery = (sql, dateStart, dateEnd, limit) => {
    return new Promise((res, rej)=> {
      db.query(sql, [dateStart,dateEnd,limit], function (err, results) {
        if (err) rej(err);
        res(results)
      });
    })
  }

  const sql = 'SELECT * FROM summary_dz WHERE Start != "" AND  Start BETWEEN ? AND ? LIMIT ?'

  const dateStart = req.params.dateStart;
  const dateEnd = req.params.dateStart;
  const limit = Number(req.params.limit);
  
 
  const results = await promiseQuery(sql, dateStart, dateEnd, limit)
  for (const counter in results) {  
    xlsSourceFilesRetrievedTsdz.push(results[counter].XlsSourceFile);
  }

  console.log(xlsSourceFilesRetrievedTsdz)
  
}

What I do here was wrap the whole thing in a Promise and return it to wait te results.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading