I am able to console the result using mysql query (using arrow function result parameter) but can't pass that data to global variable, or return as a fuction, or push into any list.
const {createPool} = require('mysql');
const pool = createPool({
host: 'localhost',
user: 'root',
password: 'root123',
database: 'accounts_db',
connectionLimit: 10
})
const sql = 'SELECT * FROM `accounts`';
var dataList = [];
pool.query(sql, (err, result, fields) => {
if (err)
console.log(err);
else {
// console.log(result); //able to see this data
dataList.push(result);
}
})
console.log(dataList); // I am getting the [] as no data get pused to list.
I also used JSON Stringfy to unpack the rawDataPacket but still unable to send that data to any veriable to use that globally.
const {createPool} = require('mysql');
const pool = createPool({
host: 'localhost',
user: 'root',
password: 'root123',
database: 'accounts_db',
connectionLimit: 10
})
const sql = 'SELECT * FROM `accounts`';
var dataList = [];
var simpleData = null;
pool.query(sql, (err, result, fields) => {
if (err)
console.log(err);
else {
// console.log(result);
dataList.push(result);
simpleData = JSON.parse(JSON.stringify(result));
console.log(simpleData); // console this statement
}
})
console.log(simpleData); // result null
This is due to how promises work with JavaScript's asynchronous code flow. And unfortunately the mysql
package has no way of awaiting the query result, however you can workaround this by awaiting a manual promise.
var dataList = await new Promise((resolve) => {
pool.query(sql, (err, result, fields) => {
if (err)
console.log(err);
else {
resolve(result);
}
})
});
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.