Sunday 21 April 2019

PHP dev using Node for the first time; stuck on world's simplest use case. I need to return a value from a DB and store it to a variable.

As the title suggest, I'm embarrassingly stuck on what I thought would be the simplest thing I had to do all day.Say I have a function called getCountOfGreenShirts. I want to hit the database, perform a simple COUNT, and store the number returned to a variable.Pseudocode:private getCountOfGreenShirts():number { var connection = await mysql.createConnection({ ... }); var count = 0; connection.query('SELECT count(*) as count FROM `shirts` WHERE `color` = "Green"', function (error, results, fields) { if (error) throw error; console.log(results[0].count); //Returns correct value count = results[0].count; }); console.log(count); //Returns 0 return count; } The class I am working on has a computed property, to be dynamically determined every time it is instantiated. The logic that drives this computed property is dependent on several values pulled from the database, such as the example above.I'm aware that my attempted approach won't work due to Node being asynchronous. I spent the day trudging through Stack Overflow and Medium, but for the life of me I can't find an example/best practice as to how to handle this simple use case. I switched from the mysql npm package to mysql2 to incorporate async/await/promise handling, but after several hours of trial and error got absolutely nowhere.If anyone can point me in the right direction, I'd really appreciate it. If you can show me a tutorial I'll gladly follow it, a video I'll gladly watch it, or any source code I'll gladly read through it. At this point, if anyone can just show me how the hell to correctly pull a value from a mysql database, I'll happily buy them Gold.

Submitted April 21, 2019 at 05:19PM by _SevenDeuce

No comments:

Post a Comment