简体   繁体   中英

Getting mysql result from javascript function in node.js

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
    });
}

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);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM