简体   繁体   中英

node.js async using SQL

I need to get the results from a query before the rest of my code (including other queries that have the same issue) executes. Right now I have a file that establishes the sql connection which looks like this:

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;

Then my API code to get the information for retrieving a work session looks like this:

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;

I believe this should work if it were to all run asynchronously, the issue is that it does not and it runs half of it before the queries are done running. Any and all help would be greatly appreciated!

Your await call only works inside of the scope of the function deemed async. Both calling getProjectReport async, and then

 var theReport = await getProjectReport(proj, weekStart, weekEnd);

will not work as expected.

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