如何在node js中返回mysql包的多个请求

kcrjzv8t  于 2023-01-12  发布在  Mysql
关注(0)|答案(2)|浏览(124)

我正在做一个项目,它有一个简单的 Jmeter 板,在我的服务器上,我建立了三个mySql连接,并获得一些信息,如**(用户、管理员、事件)**,这些信息将显示在 Jmeter 板上,我使用以下代码收集信息:

function gather_info(callback) {
  let info = {
    users: [],
    admins: [],
    events: []
  }
  sql.query("SELECT * FROM users", (err, users) => { info.users = users });
  sql.query("SELECT * FROM users WHERE isAdmin = 1", (err, admins) => { info.admins = admins });
  sql.query("SELECT * FROM events", (err, events) => { info.events = events });

  callback(info);
}

然后我在get请求中使用上面的函数:

app.get("/", loginRequired, (req, res, next) => {
//check if user is admin - to render dashboard
  if (req.user.isAdmin) {
    gather_info((info) => {
      return res.render('admin', { events: info.events, users: info.users, admins: users.admins })
    })
  };
  //if user not admin render users page
  sql.query("select * from events where userId = ?", [req.user.ID], (err, events) => {
    res.render("index", { events });
  });
})
  • 现在的问题是函数不工作正确,我尝试使用async/await但mysql不这样工作,我现在该怎么办?
  • 另一个问题是,在使用createPool时,每次打开连接时是否都应该关闭连接?
    -谢谢你的好意
zpgglvta

zpgglvta1#

您可以使用Promise.all来优化gather_info方法。

function mysqlSyncQuery(q) {
  return new Promise((resolve, reject) => {
    sql.query(q, (err, result) => { 
      if(err) return reject(err); 
      return resolve(result);
    });
  })
}

async function gather_info(callback) {
  let info = {
    users: [],
    admins: [],
    events: []
  }
  let q1 = mysqlSyncQuery("SELECT * FROM users");
  let q2 = mysqlSyncQuery("SELECT * FROM users WHERE isAdmin = 1");
  let q3 = mysqlSyncQuery("SELECT * FROM events");
  let results = await Promise.all([q1, q2, q3]);
  info.users = results[0];
  info.admins = results[1];
  info.events = results[2];
  callback(info);
}

您可以进一步在Promise.all的catch块中添加验证,还可以解析和验证结果数组。
Promise.all将并行运行这些查询,这样您就不必等待一个查询完成后再开始另一个查询。这样,由于这些查询看起来是独立的,因此速度会更快。
除此之外,您还可以使用async await重构app.get以使代码始终相似,因为您可以很容易地理解它,所以我没有涉及它。

fhg3lkii

fhg3lkii2#

至少有3种方法可以做到这一点。
1.嵌套调用,最有可能是最糟糕的!!

function gather_info(callback) {
  let info = {
    users: [],
    admins: [],
    events: []
  }
  sql.query("SELECT * FROM users", (err, users) => { 
    info.users = users;
    sql.query("SELECT * FROM users WHERE isAdmin = 1", (err, admins) => {
      info.admins = admins;
      sql.query("SELECT * FROM events", (err, events) => { 
        info.events = events;
        callback(info);
      });
    });
  });
}
  1. async/await更好,但查询是一个接一个地调用,而不是并行调用,这意味着您要等待每个查询完成后再调用另一个查询
async function gather_info(callback) {
  let info = {
    users: [],
    admins: [],
    events: []
  }
  info.users = await query('SELECT * FROM users');
  info.admins = await query('SELECT * FROM users WHERE isAdmin = 1');
  info.events = await query('SELECT * FROM events');
  callback(info);
}

function query(q) {
  return new Promise(function(resolve, reject){
    sql.query(q, (err, data) => { 
      resolve(data);
    });
  });
};
  1. Promise.all,这应该会并行运行所有查询
async function gather_info(callback) {
  let info = {
    users: [],
    admins: [],
    events: []
  }
  let users = query('SELECT * FROM users');
  let admins = query('SELECT * FROM users WHERE isAdmin = 1');
  let events = query('SELECT * FROM events');

  Promise.all([users, admins, events]).then((values) => {
    info.users = values[0];
    info.admins = values[1];
    info.events = values[2];
    callback(info);
  });
  
}

function query(q) {
  return new Promise(function(resolve, reject){
    sql.query(q, (err, data) => { 
      resolve(data);
    });
  });
};

相关问题