0

I am trying to get MySQL to result from the function. At moment I am trying to set results from function to global array, but this doesn't work.

I am not very familiar with NodeJS or Javascript but I think it's a scope issue.

How would one do this in a proper way? Do I need to use async or maybe return results from a function?

This is what I have at moment.

const mysql = require('mysql');
const connection = mysql.createConnection({
  host     : 'xxxx',
  port     : '3306',
  user     : 'xxxx',
  password : 'xxxx',
  database : 'xxxx'
});

var db_members =[];
get_members();
console.log(db_members); //outputs []

function get_members(){
    connection.query("SELECT * FROM users", (err, result, fields)=>{
        if (err) throw err;
        result.forEach(function(row) {
            db_members.push(row.username);
        });
        console.log(db_members); //this works
    });
}

1 Answer 1

1

connection.query is async function so you are not able to get the result synchronously.

It is needed to make get_members to return Promise as the return value so to get the result asyncronously when using it..

const mysql = require('mysql');
const connection = mysql.createConnection({
  host     : 'xxxx',
  port     : '3306',
  user     : 'xxxx',
  password : 'xxxx',
  database : 'xxxx'
});

function get_members() {
  return new Promise((resolve, reject) => {
    connection.query("SELECT * FROM users", (err, result, fields)=>{
        if (err) return reject(err);
        var db_members = [];
        result.forEach(function(row) {
            db_members.push(row.username);
        });
        return resolve(db_members);
    });
  });
}

get_members()
  .then((members) => {
    console.log(members); // This will work.
  })
  .catch((error) => {
    console.error(error);
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.