node.js 异步使用 SQL
Posted
技术标签:
【中文标题】node.js 异步使用 SQL【英文标题】:node.js async using SQL 【发布时间】:2021-07-29 04:13:09 【问题描述】:我需要在执行其余代码(包括具有相同问题的其他查询)之前从查询中获取结果。现在我有一个建立 sql 连接的文件,如下所示:
const mysql = require("mysql");
const config = require("./configuration/config.json");
var conn = mysql.createConnection (
host: config.host,
user: config.user,
password: config.password,
database: config.database
);
module.exports = conn;
然后我获取信息以检索工作会话的 API 代码如下所示:
const bodyParser = require("body-parser");
const router = require("express").Router();
const conn = require("../mysqldb");
router.get("/", async (req, res) =>
console.log(`GET class report called for: project = $req.query.project and week of $req.query.date`);
var date = req.query.date;
var proj = req.query.project;
var theReport = [];
//Might not need date info
var weekStart = new Date(date);
var weekInMilliseconds = 7 * 24 * 60 * 60 * 1000;
var weekEnd = new Date();
weekEnd.setTime(weekStart.getTime() + weekInMilliseconds);
const getProjectReport = async (proj, start, end) =>
console.log(`getProject called for project $proj within date $date & $weekEnd`);
var uids = [];
// Find the sessions given the date and the project code
let sql = "select uid from user;"
conn.query(sql, (err, rows) =>
if (err)
return res.status(500).json( error: err );
else
for (let l = 0; l < rows.length; l++)
uids.push(rows[l]);
);
let qry = "SELECT * FROM work_session WHERE date BETWEEN (DATE('" + date + "')) AND (DATE('" + date + "') + 6) AND project = '" + proj + "';"
conn.query(qry, (err, rows) =>
if (err)
return res.status(500).json( error: err );
else
//for all users in DB
for (let u = 0; u < uids.length; u++)
let timeWorked = 0.0;
let sessions = [];
//for all work sessions
for (let w = 0; w < rows.length; w++)
if (uids[u].uid == rows[w].uid)
timeWorked = timeWorked + hoursWrked(rows[w].starthr, rows[w].startmin, rows[w].finishhr, rows[w].finishmin);
sessions.push(rows[w]);
//If there was time works (AKA if a user with data was found and info recorded)
if (timeWorked > 0)
// Query for user information
let qry = "select * from user where uid = " + uids[u].uid + ";"
conn.query(qry, (err, rows) =>
if (err)
return res.status(500).json( error: err );
else
var jsonString = email: rows[0].email, hours: timeWorked, lname: rows[0].lname, fname: rows[0].fname, sessiontimes: sessions, weekS: req.query.date, weekE: weekEnd ;
theReport.push(jsonString);
);
);
//return the report
return theReport;
function hoursWrked(startHr, startMin, finishHr, finishMin)
let hours = finishHr - startHr;
let minutes = finishMin - startMin;
if (hours < 0)
hours = hours + 24;
if (minutes < 0)
minutes = minutes + 60;
hours = hours - 1;
let time = hours + minutes / 60;
totalTime = Math.round(100 * time) / 100;
return totalTime;
var theReport = await getProjectReport(proj, weekStart, weekEnd);
console.log(theReport);
if (theReport[0])
console.log("Got it");
return res.status(200).send(theReport);
else
console.log("darn");
return res.status(400).send( msg: "No projects/users found." );
);
module.exports = router;
我相信如果它全部异步运行,这应该可以工作,问题是它没有,并且在查询完成运行之前它运行了一半。任何和所有的帮助将不胜感激!
【问题讨论】:
【参考方案1】:您的 await 调用仅在视为异步的函数范围内有效。两者都调用 getProjectReport 异步,然后
var theReport = await getProjectReport(proj, weekStart, weekEnd);
不会按预期工作。
【讨论】:
那么如何解决这个问题?我尝试在 getProjectReport 异步函数的括号内移动该行,但仍然有问题以上是关于node.js 异步使用 SQL的主要内容,如果未能解决你的问题,请参考以下文章