How to populate array outside function clause in nodejs
P粉714844743
P粉714844743 2024-02-21 18:49:57
0
1
457

I want to populate 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 in xlsSourceFilesRetrievedTsdz. Is there anything wrong with what I wrote? I get an empty array. The console.log inside the block in the comment gives the desired result, how can I get it from outside the block?

P粉714844743
P粉714844743

reply all(1)
P粉759457420

This should work:

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 did here was wrap the whole thing in a Promise and return it to wait for the result.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template