Function returns "undefined" [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
My function returns "undefined", when I am waiting "result". What is a problem?
getUserDictionary = (user_id) => {
connection.connection.query("SELECT eng_word, ru_word FROM `dictionary` where user_id="+user_id,
function (error, results, fields) {
if (error) throw error;
console.log(results);
return results;
});
}
console.log(getUserDictionary(1));
"results" shows what I want (no problem with Data base connection).
But last console.log with function returns undefined

You are leaving yourself wide open to a SQL injection attack
Do not do this: "SELECT eng_word, ru_word FROM dictionary where user_id="+user_id
If this is just a pet project, fine, but if you're opening it up to the internet anyone could erase your database. Use prepared statements instead. If you are using mysqljs you can drop this in as a replacement for your current query:
connection.query('SELECT eng_word, ru_word FROM dictionary WHERE user_id = ?', [user_id], function (error, results, fields) {
Anyways...
Your problem is that connection.connection.query() is an asynchronous function. If you would like it to behave synchronously, you can use the async/await pattern supported in ES6. Otherwise, you can structure your code to act in response to the return from query().
Here is what it would look like using async/await:
getUserDictionary = (user_id) => {
return new Promise((resolve, reject) => {
connection.connection.query("blah blah blah",
function (error, results, fields) {
if (error) {
reject(error);
return;
}
console.log(results);
resolve(results);
});
});
};
Which you can use like
async () => {
let results = await getUserDictionary(0);
console.log(results);
}

Related

Function returning "undefined" while trying to query database in node.js

This piece of code always returns undefined to the calling function. I'm new to JavaScript and I did try and look into some of the callback solutions on Stack Overflow and other resources but none of them worked for me. Any help with this would be highly appreciated. Thank you!
var funcs = require('./index.js');
var connected = require('./database')
query='SELECT * from trades'
const res = execute_rows(query)
console.log(res)
function execute_rows(query){
con = connected();
con.query(query, function(err, result, fields) {
if (err) {
return console.log(err);
}
console.log(result) //Displays correct results
return result; // Returns undefined to calling function
})
con.end();
}
Harshith
Ok, if you print de result of your query inside the function execute_rows just before de return statement you should be able to see it.
The problem with your function is your not actually returning the result "on time".
You need to return a promise to get the result from your function.
This could be a little hard to understand when you're new in JS. Your function should be something like this:
function execute_rows(query){
con = connected();
return new Promise((resolve, reject) => {
con.query(query, function(err, result, fields) {
if (err) {
// Returning the error
reject(err);
con.end();
}
resolve(result);
con.end();
});
});
}
Now, when you call you call your function, you have two options:
Use async/await
Still using promises (callback-driven)
Calling your function:
const dbResult = await execute_rows(query);
or
execute_rows(query).then(result => {
// Get the result
console.log('result:', result);
}).catch(error => {
// Get the error
console.log('error:', error);
});
Please, read about promises and async/await pattern!
Links:
Promises:
https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Promise
Async/await:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await

Node.js mysql import query result outside function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I am making a website where i need to import data from database and use it later in program. But when i am using npm package mysql i can't find any way to import result of query outside function for later use. Here is an example of my code.
Function with that i get data from database:
let output;
dba.query('SELECT * FROM `movies-web`.movies;',(err, rows) => {
if(err) {
throw err;
} else {
output = rows;
}
});
And in code i use it like this:
res.write(output);
But the variable output return undefined.
I am solving this problem for longer than month, i browsed so many pages, questions here on stackoverflow and i can't find working solution.
You can't write code like that, I suggest you read about callback documents and learn how to use asynchronous in the node is
https://nodejs.org/en/knowledge/getting-started/control-flow/what-are-callbacks/
https://www.w3resource.com/node.js/nodejs-programming-model.php
https://stackoverflow.com/a/19739852/6759368
Your code should write like that:
dba.query('SELECT * FROM `movies-web`.movies;',(err, rows) => {
if(err) {
throw err;
} else {
res.write(rows)
}
});
P.S:
A better scenario for use callback:
const http = require('http');
function executeQuery(next) {
dba.query('SELECT * FROM `movies-web`.movies;',(err, rows) => {
if(err) {
console.error(err);
next(err);
return
}
next(null, rows);
});
}
const server = http.createServer(function (req, res) {
executeQuery(function (error, output) {
if (error) {
res.writeHead(400);
res.end(error.message);
return;
}
res.writeHead(200);
res.end(JSON.stringify(output));
});
});
server.listen(8080);

Function returning undefined seems like console.log is running before result is returned? Promise needed? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have a function in another file that I want to get the response of and then do something with that response before exiting my controller function.
Here is the code from the required file:
exports.counter = function(companyID) {
options.json.companyID = companyID
request.post('/monitorCounter', options, (error, response, body) => {
if (error) {
console.log(error);
throw error;
}
if(body.success == true) return true
});
}
Here is how I am requiring the file/function
const monitorCounter = require('../controllers/counter').counter
Then this is how I am trying to test/use it in my main controller file
let valid = monitorCounter(companyID)
console.log(`Valid: ${valid}`)
I am expecting it to return true (tested via console.log and function works as expected), but I am getting undefined.
I was thinking that I need a promise for this but was not sure how to do it with it being a different file and I'm also not up to date fully yet on promises (working on that currently)
I managed to figure out how to do the promise I needed, I had tried before but was not 'return'ing a promose and was calling resolve/reject wrong. Below is working code for this issue.
exports.counter = function(companyID) {
return new Promise((resolve, reject) => {
options.json.companyID = companyID
request.post('/monitorCounter', options, (error, response, body) => {
if (error) {
console.log(error);
throw error;
}
if(body.success == true) resolve(true)
if(body.success != true) reject(false)
});
});
}

Console loggin a MongoDB collection. Undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I'm creating a Node project cause i want to knwo how to use mongoose but i'm facing a problem right now. I'm getting an undefined variable while returing a collection from my MongoDB database. This is my code:
app.js
...
case 'index-user':
let indexUserResponse = userController.index();
console.log(indexUserResponse); // undefined
break;
...
user.js (controller)
...
const index = () => {
User.find({}, function(err, res) {
if (err) throw err;
return res;
});
}
...
I know that there is a user on the database and i can see it if add a console.log(user) just before the return res; so... What is happening here? I don't get it.
The issue is that userController.index() is an calling an async function.
You should use a callback or a promise in order to fetch the data from you db.
Promise example:
Here we are returning a promise from the the executing the query on the Users collection.
const index = () => User.find({}).exec();
And in app.js:
case 'index-user':
userController.index().then(result => {
console.log(result); // as you use find there will be a list of user documents
});
break;
Or, you can use good old callbacks as so:
const index = (callback) => {
User.find({}, function(err, res) {
if (err) throw err;
return callback(res);
});
}
And in app.js:
case 'index-user':
let indexUserResponse = userController.index((result) => {
console.log(result);
});
break;
When you execute it the way you do now, the console.log() runs before the index() method can execute the find() callback.
Hope it's clear enough and helps

Using a db query as a promise [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I'm trying to use sql queries as promises. I can't seem to get it to work:
query: (sql, args) => {
if (args) sql = mysql.format(sql, args);
return new Promise((resolve, reject) => {
pool.getConnection((err, connection) => {
if (err) {
console.log(err);
reject(Error(err.code));
}
connection.query(sql, (err, results) => {
connection.release(); // always put connection back in pool after last query
if (err) {
console.log(err);
resolve([]);
}
resolve(results);
});
});
});
},
And here is the query itself:
async function dbCall(sql, arg) {
let data = await db.query(sql, arg);
console.log(data);
data = data[0];
return data;
}
And here is the pool:
var pool = mysql.createPool({
host: 'localhost',
user: 'user',
password: 'pass',
database: 'db',
});
What I'm trying to do:
I'm trying to have it where it doesn't get hung up on async functions. I want it to return a value throughout a whole async function instead of inside of itself only.
Right now, it isn't working at all. However, when it is I would like row to be defined in my whole function instead of just inside the db.query.
I'm not sure if this makes sense, but if you need more clarification just ask anything.
Well if I understand your questions correctly you're misunderstanding how promises should be handled. Promises make use of a then() function to perform something only after the async request is finsihed.
It reads pretty well in plain English. Perform my async request THEN do something with the data.
Try this:
db.query(userSQL, username).then(res => console.log(res))
Additionally, you could use an async function. This allows use to handle async functions in a similar way to synchronous functions where your code will be executed sequentially without having to worry about chaining and nesting other code inside of then() functions
async function dbCall() {
let data = await db.query(userSQL, username);
console.log(data);
}
As a side note. This was super helpful to me when I was first getting into Promises.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Categories

Resources