Home > Net >  how to fill an array outside the function clause in nodejs
how to fill an array outside the function clause in nodejs

Time:04-29

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?

CodePudding user response:

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.

  • Related