0

Edit: Here is my full code that throws no errors:

router.get('/:id/all', async (req, res, next) => {
    let id = req.params.id;
    let t;                         
    let d;                         
    let o;                         
    let p;
    let data = [];
    let entry = {};
    try {
        let rowConfig = await methods.runQuery('SELECT SystemID, Begin, End, Power FROM Configuration WHERE ID = ?', id);
        p = rowConfig[0].Power;
        let begin = rowConfig[0].Begin;
        let end = rowConfig[0].End;
        let counter = [Var1, Var2, Var3];
        
        let result = await methods.runQuery('SELECT * FROM Table1 WHERE ID = ?', id);
        result.forEach(async function(row) {
            let resultT;
            if (!row.EventStop) {
                t = row.EventBegin - begin;
                resultT = await methods.runQuery('SELECT EventBegin, EventStop FROM Table1 WHERE ID = ? AND RootID IN (4, 5) AND IsValid = TRUE AND EventBegin < ?', [id, row.EventBegin]);
            }
            else {
                t = row.EventStop - begin;
                resultT = await methods.runQuery('SELECT EventBegin, EventStop FROM Table1 WHERE ID = ? AND RootID IN (4, 5) AND IsValid = TRUE AND EventBegin < ?', [id, row.EventStop]);
            }
            console.log(t);
            d = 0;
            resultT.forEach(function(row) {
                let dt = row.EventStop - row.EventBegin;
                d = d + dt;
            });
            o = t - d;
            console.log(o);
            entry = {'1': t, '2':o};
            data.push({entry});
        });
    } 
    catch (error) {
        res.status(500).send({ error: true, message: 'Error' });
    }
    return res.send({ data: data });
});

But the data array that is sent remains emtpy! So i looked in my console and two stand out.

  1. The values of tand o are wrong
  2. They get logged in the console when the get method already has finsihed. So when the data array is sent, obviously there are no entry in there.

The order in which the code should be excuted:

For each row of Table1 i want to have t and o, so it should be:

forEach loop (row1)

-> if/else -> calculate t

-> get resultT

-> forEach loop (row1)

-> calculate d

-> forEach loop (row2)

-> calculate d

-> ...

-> calculate o

-> push entry to data

-> forEach loop (row2)

-> ...


I am working with node and express for creating a Rest API. I am currently struggling because of the asynchronous behaviour of node. This is what I am trying to achieve:

In a get method, I want to collect all the data of table from my database.

router.get('/:id/all', async (req, res, next) => {
...
try {
let result = await methods.runQuery('SELECT SystemID, Begin, End, Power FROM Configuration WHERE ID = ?', id);

The runQuery method looks like this :

module.exports.runQuery = function(sql, parameter){
return new Promise((resolve, reject) => {
    dbConn.query(sql, parameter, function (error, result, fields) {
      if (error) reject(error);
      else {
        resolve(result);
      } 
    });
  });
}

This works so far. Now my problems start. For each row of this table I want to do something. Inside this for loop I need to do calculations that depend on each other. }

2 Answers2

2

As I have mentioned in the comment, await won't work in forEach loop. Try for...of loop instead.

Example:

for (let row of result) {
  // await will work here
}
Shihab
  • 2,641
  • 3
  • 21
  • 29
1

for/forEach loops in javascript are not promise/async/await aware so you will need to use Promise.all instead of for loop. Basically something like

Promise.all(result.map(result => doSomethingAsync()))

Make sure there are not large data in result as you will be spinning those many promises in parallel. Better will be to use promise batch or streaming.

Ashish Modi
  • 7,529
  • 2
  • 20
  • 35