如何在nodejs中的函数子句之外填充数组
P粉714844743
P粉714844743 2024-02-21 18:49:57
0
1
466

我想在功能块之外填充一个数组

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)

我要填写xlsSourceFilesRetrievedTsdz。我写的有什么问题吗?我得到一个空数组。注释中块内的 console.log 给出了想要的结果,如何从块外部获取?

P粉714844743
P粉714844743

全部回复(1)
P粉759457420

这样做应该有效:

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)
  
}

我在这里所做的是将整个事情包装在一个 Promise 中并将其返回以等待结果。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板