[Nodejs] Issue when mapping over MySQL output - Logs too early

Hi folks,
when I have my function that is getting data from MySQL I want to iterate over each row and work with the data using another function. I use a console.log to see the result and what I get is NaN while the operations are running. So the log is not waiting for the map function to finish. Why’s this? Or how can it be fixed?

Here’s the function’s code:

let postKittenGrade = async (req, res) => {

  var sum_ash1 = 0;
  var sum_ash2 = 0;
  var ratingOutput = '';
  const [row_getKittenPosts] = await dbConnection.execute(
    "SELECT * FROM users_ratings WHERE get_user_id = ? AND kitten_id = ? AND creation > DATE_SUB(CURDATE(), INTERVAL 30 DAY)",
    [1, 1]
  );
  row_getKittenPosts.map(async item => {  
    console.log(item+item["post_user_id"]);
    var getRating = await absoluteShare(item["post_user_id"],item["get_user_id"],item["kitten_id"],item["kitten_rating"])
    console.log(getRating)
    sum_ash1 = sum_ash1+getRating[0];
    sum_ash2 = sum_ash2+getRating[1];  
    console.log(sum_ash2/sum_ash1)  
  })

  ratingOutput = sum_ash2/sum_ash1;
  console.log(ratingOutput)

  res.send(ratingOutput)

}

Thank you, folks.

There are no easy answers here. You can see this search for a bunch of leads on using map() with async functions and adapt one. Most recent solutions involve using Promise.all() and async. I have found before that looping with for avoids this problem with await/async.

As far as the console.log() calls, they have their own problems with asynchronous data. I’ve posted here about it before (because it’s so easy to forget and mess up), but if you have to get some data out and it may be asynchronous, you really need to use some of the JSON output functions (stringify, etc.) or use a logging library (like winston) that can cope.

It’s really not a bad idea in general to start using loggers (like winston) early on and log at the debug level instead of using console.log() because then you can configure the logging level and the output is available when you need it throughout the lifespan of the project.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.