Zarvix
Zarvix

Reputation: 119

async function with mysql query won't return query results node.js

I have a function that queries a mysql database with a select query. This is all inside an async function. The query keeps telling me on the return line that it cannot find the variable "rollStatus".

async function PullRollStatus(){
     return new Promise((resolve,reject)=>{

     var sql = `SELECT * FROM brawlid${brawlID}`
     con.query(sql, (error, rows, fields) => { 

     var rollStatus= []
     for (var i in rows) {
     rollStatus.push(rows[i].Bakuganrolled)
         }

     })
     console.log(rollStatus)
     return rollStatus
     })
 }

     var rolledcheck = await PullRollStatus();
     console.log(rolledcheck)

I've never used new Promise before, as async functions are still kind of new to me. I have tried this without the "return new Promise" line and with it, both giving the same result. I have referenced this async and await on MySQL call in node js and I'm still getting some problems or it might be confusing me more, I don't know. Any help is greatly appreciated. Thanks in advance!

Upvotes: 0

Views: 1478

Answers (1)

Three D Fish
Three D Fish

Reputation: 163

I would have to know a bit more about the database and the value of brawlID, but you don't use return with promises instead you use resolve and reject, also, you are returning a promise, do you don't use async. Here is an edited example. Note I use mysql.format to pass the variable into the query, this will safeguard against code injection.

Also, I would think you would be using a where statement, unless you have a table for each brawlID, but it would make for sense if brawlID is a column in the table. I changed the function to take the value of brawID passed parameter instead of referencing a global variable.

const mysql = require("mysql2/promise");

const mysqlconfig = {
  host: "localhost",
  user: "youruser",
  password: "yourpassword"
  database: "yourdb"
  multipleStatements: true
};

const con = mysql.createConnection(msqlconfig);

function to (promise) {
    return promise
        .then(val => [null, val])
        .catch(err => [err]);
}

function PullRollStatus(brawlID){
     return new Promise((resolve,reject)=>{

       let sql = `SELECT * FROM brawlid WHERE brawlID=?`;
       mysql.format(sql,brawlID);
       con.query(sql, (error, rows, fields) => { 
         if (error) {
           reject(error);
         } else {
           let rollStatus = [];
           for (let row of rows) {
             rollStatus.push(row.Bakuganrolled)
           }
           console.log(rollStatus);
           resolve(rollStatus);
         }
       });
     });
 }

let brawlIDtoCheck = 1;

let [err,rolledcheck] = await to(PullRollStatus(brawlIDtoCheck));
if (err) {
  console.log("encountered err",err);
}
console.log(rolledcheck)

Upvotes: 1

Related Questions