Skip to content Skip to sidebar Skip to footer

I Want To Take Out The Result From Mysql's Connection.query And Save It In Global Scope Chain In Nodejs

I tried bringing out result by storing in variable current product. But I cant use it outside the function, so my array returns empty var connection = mysql.createConnection({

Solution 1:

Try to use async/await syntax to get your results

const mysql = require('mysql'); // or use import if you use TSconst util = require('util');
    const conn = mysql.createConnection({
   host: config.config.mysql.opencart_local.host,
     user: config.config.mysql.opencart_local.user,
      password: config.config.mysql.opencart_local.password,
      database: config.config.mysql.opencart_local.database
     });
    var current_products = [];
    // var query_current_products = 'select * from table;';

    (asyncfunctiongetProducts () => {
      try {
        const rows = awaitquery( query_current_products);
        console.log(rows);
        current_products=rows;
      } finally {
        conn.end();
      }
    })()

Solution 2:

use this code:

var query_current_products = 'select * from users';
var current_products = [];
functionf() {
    returnnewPromise(resolve => {
        con.connect(function (err) {
            if (err) throw err;
            console.log("Connected!");
            con.query(query_current_products, function (err, result) {
                if (err) throw err
                resolve(result);
            });
        });
    })
}

asyncfunctionasyncCall() {
    current_products = awaitf();
    console.log("outside callback : ", current_products);
}

asyncCall();

Post a Comment for "I Want To Take Out The Result From Mysql's Connection.query And Save It In Global Scope Chain In Nodejs"