-3

I would like to wait until the database return values are complete and then display them in HTML using a view. Unfortunately, despite async and wait, I always get the return value

"undefined".

but the database query returns values as you can see in the console output inside getSensorData() function.

app.post("/lesen", async function(request, response){         
    //get ID
    let FzID = request.body.ID;
    console.log(FzID);

    //get Data for ID from DB
    let data = await db.getSensorData(FzID);

    console.log("DB response: " + data);


    //create view
    const body = view.createView(JSON.stringify(data));
    response.send(body);
});
//MariaDB
const mariadb = require('mariadb');
const pool = mariadb.createPool({
  host: "127.0.0.1",
  port: 3307,
  database: "mydatabase",
  user: 'myuser',
  password: 'mypasswd',
  connectionLimit: 5,
  connectTimeout: 5000,
  //rowsAsArray: true //Returns result-sets as arrays, rather than JSON.
  //This is a faster way to get results. For more information, see Query.
});

async function getSensorData(data) {
  console.log("MariaDB.getSensorData(" + data + ")...");

  let db;
  try {
    console.log("getConnection()..");
    db = await pool.getConnection();
    const rows = await db.query("SELECT * from sensordaten WHERE UID=?", data);

    console.log("from DB connection:")
    console.log(rows); //[ {val: 1}, meta: ... ]

    return rows;

  } catch (err) {
    throw err;
  } finally {
    if (db) return db.end();
  }
}

module.exports = {
  getSensorData
};

the output on console:

getConnection()..
from DB connection:
[
  {
    ID: 1,
    UID: 'e123',
    LogDate: 2023-03-23T12:30:00.000Z,
    SensorName: 'TestSensor',
    SensorValue: '28.00'
  },
  {
    ID: 2,
    UID: 'e123',
    LogDate: 2023-03-23T12:31:00.000Z,
    SensorName: 'TestSensor',
    SensorValue: '28.29'
  }
]
DB response: undefined

why is the data on console log inside the db query function but not after that available ?

I read about all the other Question but i dont understand clearly. The async function is from mariadb -> get startet.. Thank you!

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Ringo
  • 5
  • 3

1 Answers1

0

Take the return statement out of the finally clause. It's overriding the return value of the main try block, since it executes whenever you leave the try. Since db.end() returns undefined, that's what the function returns.

  } finally {
    if (db) db.end();
  }
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks! that was the Problem i have overseen. How can i access then easily the JSON Parts in data ... like data.ID or data.UID or data.LogDate .... ? – Ringo Mar 24 '23 at 08:35
  • got it: data[0].ID ->works – Ringo Mar 24 '23 at 09:23