简体   繁体   中英

ExpressJS MySql Pool Connection Query Return

I am just starting in ExpressJS. So here console.log works, so if I make a call, I do see it in terminal result dataset printed. But, it doesn't return it as response. I do console.log and return but still get no data in response..

index.js

...
app.get("/", async (req, res) => {
  let data = await queries();
  res.json(data);
});
...

Also tried

...
app.get("/", (req, res) => {
  res.json(queries());
});
...

queries.js

function main(sql) {
  return pool.getConnection((err, connection) => {
    if (err) throw err;
    return connection.query(sql, (errt, rows) => {
      connection.release(); // return the connection to pool
      if (errt) throw err;
      console.log(rows);
      return rows;
    });
  });
}
function queries() {
  let Q = "SELECT * FROM `items`";
  return main(Q);
}

I believe the problem is in the function main() if you do see the result in the terminal. Your functions in the index.js file seems okay. The issue is probably due to the promise not being sent back from the main() function in queries.js file. You need to do 2 things -

  1. Wrap the functionality of the main() in a Promise and return that promise. The callback function of the Promise object takes resolve (use this to return result) and reject (use this to return error).

  2. As the main() will return a promise, you queries() function needs to be async, therefore needs to await the return from the main().

I have attached an Image to show how I implemented this for a DNS-lookup function. You will find some similarities.

返回承诺的示例函数

 // Notice the resolve and reject are functions function main(sql) { return new Promise((resolve, reject) => { pool.getConnection((err, connection) => { if (err) throw err; connection.query(sql, (errt, rows) => { connection.release(); // return the connection to pool if (errt) throw err; console.log(rows); resolve(rows); }); }); }); } async function queries() { let Q = "SELECT * FROM `items`"; let result = await main(Q); return result; }

I believe this should work. Give it a try and good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM