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粉7594574202024-02-22 11:05:55
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.