I try to store the result of my mysql request into and async function (to make something after storing my result) but it's returning undefined.. I don't know why
function hh () {
connection.query('SELECT * FROM `rounds` ', function (error, results, fields) {
if (error) throw error;
// console.log(results)
return results
});
}
async function run() {
connection.connect();
let deter = await hh();
console.log(deter)
connection.end();
}
run();
You're not returning a promise... Try with this code, it could help...
function hh () {
return new Promise((resolve, reject) => {
connection.query('SELECT * FROM `rounds` ', function (error, results, fields) {
if (error) return reject(error);
// console.log(results)
resolve(results)
});
});
}
async function run() {
connection.connect();
let deter = await hh();
console.log(deter)
connection.end();
}
run();
Related
I have a node.js project with mvc architectures,
I am trying to connect it to mysql database, and write a query,
I get the query result, but when I try to call the function that declare the query, I get an empty result,
I guess so it because of the query calling is async.
in my model:
exports.getAllUsers = function () {
con.connect(function (err) {
if (err)
console.log('error')
else
con.query("SELECT * FROM Users", function (err, result, fields) {
if (err) throw err;
else {
return result;
}
});
});
}
in my controller:
exports.get_all_users = function (req, res) {
var arr = UserModel.getAllUsers();
res.send(arr);
}
the arr in get_all_users function is always undefined,
what can be the problem???
There are three options you could use in node.js.
These are simple code for demo three style, they still have a lot space for improvement.
callback style
exports.getAllUsers = function (callback) {
con.connect(function (err) {
if (err)
console.log('error')
else
con.query("SELECT * FROM Users", function (err, result, fields) {
if (err) throw err;
else {
callback(result);
}
});
});
}
exports.get_all_users = function (req, res) {
UserModel.getAllUsers((result) => {
res.send(result);
});
}
promise style
exports.getAllUsers = function () {
return new Promise((resolve, reject) => {
con.connect(function (err) {
if (err)
console.log('error')
else
con.query("SELECT * FROM Users", function (err, result, fields) {
if (err) throw err;
else {
resolve(result);
}
});
});
})
}
exports.get_all_users = function (req, res) {
UserModel.getAllUsers().then(result) => {
res.send(result);
});
}
async-await style
promise style
exports.getAllUsers = function () {
return new Promise((resolve, reject) => {
con.connect(function (err) {
if (err)
console.log('error')
else
con.query("SELECT * FROM Users", function (err, result, fields) {
if (err) throw err;
else {
resolve(result);
}
});
});
})
}
exports.get_all_users = async function (req, res) {
const result = await UserModel.getAllUsers();
res.send(result);
}
After inserting a row into mysql, I am trying to retrieve the row ID.
con.query('INSERT INTO terminals SET ?', {title: 'test'}, function (err, result, fields) {
console.log(result.insertId);
});
Now I am trying to access result.insertId outside of the function. How is this possbile using async/await?
This didn't work for me:
const response = await con.query('INSERT INTO terminals SET ?', {title: 'test'}, async function (err, result, fields) {
return result;
});
console.log(await response.insertId);
you can create a function that will return a promise.
for example:
function asynqQuery(query, params) {
return new Promise((resolve, reject) =>{
con.query(query, params, (err, result) => {
if (err)
return reject(err);
resolve(result);
});
});
}
try {
const response = await asynqQuery('INSERT INTO terminals SET ?', {title: 'test'});
console.log(response.insertId);
} catch (e) {
console.error
}
Or you can try using "promisify" from the "util" library.
Try with this:
response[0].insertId
in:
const response = await con.query('INSERT INTO terminals SET ?', {title: 'test'}, async function (err, result, fields) {
return result;
});
console.log(response[0].insertId);
Result are always an array almost it have only 1 element
Can't I use promise for nodeJS mysql query?
// My DB settings
const db = require('../util/database');
db.query(sqlQuery, [param1, param2])
.then(result => {
console.log(result);
})
.catch(err => {
throw err;
});
It is returning: TypeError: db.query(...).then is not a function
You mentioned in the comments that you want logic after the query block to be awaited, without placing that logic inside of the callback. By wrapping the method with a Promise, you can do that as such:
try {
const result = await new Promise((resolve, reject) => {
db.query(sqlQuery, (error, results, fields) => {
if (error) return reject(error);
return resolve(results);
});
});
//do stuff with result
} catch (err) {
//query threw an error
}
Something like this should work
function runQuery(sqlQuery){
return new Promise(function (resolve, reject) {
db.query(sqlQuery, function(error, results, fields) {
if (error) reject(error);
else resolve(results);
});
});
}
// test
runQuery(sqlQuery)
.then(function(results) {
console.log(results)
})
.catch(function(error) {
throw error;
});
mysql package does not support promise. We can use then only a function call returns a promise.You can use mysql2 which has inbuilt support for Promise. It will also make your code more readable. From mysql2 docs:
async function main() {
// get the client
const mysql = require('mysql2/promise');
// create the connection
const connection = await mysql.createConnection({host:'localhost',
user: 'root', database: 'test'});
// query database
const [rows, fields] = await connection.execute(query);
// rows hold the result
}
I would aslo recommend you to learn about callbacks, promise and async-await
I tried to get result using mysql database query from called function but do not wait for result in called function. Following is my code for users.js file. I got result in getBankDetail function but do not get result in users function.
var db = require("../db/mysqlconnection");
function users(app){
app.get("/users",async function(req, res, next){
let bankDetail = await getBankDetail();
console.log("bankDetail",bankDetail); //Here I do not got result
return res.send(bankDetail);
});
}
async function getBankDetail(){
db.getConnection(async function(err, connection) {
if (err) throw err; // not connected!
await connection.query('SELECT * FROM bank', function (error, results, fields) {
connection.release();
if (error) throw error;
console.log("bank result",results); //Here I got result
return results;
});
});
}
module.exports = users;
My Question is why do not wait for result in called function? I also used async/await functionality.
function getBankDetail(){
return new Promise((resolve, reject) => {
db.getConnection(function(err, connection) {
if (err) reject(err); // not connected!
connection.query('SELECT * FROM bank', function (error, results, fields) {
connection.release();
if (error) reject(err);
console.log("bank result",results); //Here I got result
resolve(results);
});
});
});
}
And then you can use let bankDetail = await getBankDetail();
If you want to use await on your db.getConnection and connection.query you will have to use mysql2/promises library or promisify those functions yourself
Here is the implementation when you use the promisified version of your database driver:
async function getBankDetail(){
const connection = await db.getConnection();
const data = await connection.query('SELECT * FROM bank');
connection.release();
console.log("bank result", data[0]); //Here I got result
return data[0];
}
I want to return the MySQL result into a variable.
I tried the following but it's not working, as I am getting an empty variable.
const mysql = require('mysql');
const db = require('../config/db');
const connection = mysql.createConnection(db);
module.exports = class Categories {
constructor (res) {
this.res = res;
}
getCategories() {
connection.query("SELECT * FROM `categories`", (error, results, fields) => {
if (error) throw error;
this.pushResult(results);
});
}
pushResult(value) {
this.res = value;
return this.res;
}
};
Just made a callback function first:
var Categories = {
getCategories: function (callback) {
connection.query("SELECT * FROM `categories`", (error, results, fields) => {
if(error) { console.log(err); callback(true); return; }
callback(false, results);
});
}
};
And then used it with route:
app.get('/api/get_categories', (req, res) => {
categories.getCategories(function (error, results) {
if(error) { res.send(500, "Server Error"); return; }
// Respond with results as JSON
res.send(results);
});
});