This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
I'm writing a basic user creation system in Node.js and I want to find out what the results of the createUser function are. The code itself works fine, with new users being posted, and already existing users being stopped. I would like to show this to the end user, so I setup a variable to return a numeric value representing what the outcome was.
The problem is, the value is never assigned to. The final console log always reads undefined, even though my other log statements appear. I feel like this is more of a JavaScript syntax question, but I am stumped.
User.prototype.createUser = function () {
console.log('Begin createUser...');
var email = this.email;
var wasUserCreated; <------- variable to assign
pg.connect(process.env.DATABASE_URL, function (err, client) {
if (err) {
console.log(err.message, err.stack);
wasUserCreated = 0; <------assigning to variable?
}
else {
var query = client.query('SELECT email FROM users WHERE email=$1', [email],
function (err, results) {
if (results.rows.length > 0) {
console.log('That email address has already been registered!');
wasUserCreated = 1; <------assigning to variable?
}
else {
console.log('Email address not found, inserting new account');
insertNewUser();
wasUserCreated = 2; <------assigning to variable?
}
});
}
});
console.log("wasUserCreated: " + wasUserCreated); <------always reads 'undefined'
return wasUserCreated;
};
This is due to your query being asynchronous - what your createUser method should do is take a callback as an argument, and invoke cb(err, wasUserCreated, user) or something inside the callback to your query.
Your console.log is always undef because it fires synchronously
some basics in mixu's node book
the 2nd argument of pg.connect is a callback function, which runs asynchronously... so the function returns before the wasUserCreated is modified
Related
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm trying to access a local variable outside the function since a few hours. I don't know where my mistakes is. The code looks like:
Edited code:
if (lastMsg.toUpperCase().indexOf("#TEST") > -1) {
var myPythonScriptPath = 'my_script.py';
var myMessage = '';
// Use python shell
const {PythonShell} = require("python-shell");
var pyshell = new PythonShell(myPythonScriptPath);
pyshell.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message);
myMessage = message;
});
// end the input stream and allow the process to exit
pyshell.end(function (err) {
if (err){
throw err;
};
});
sendText = `${myMessage};`
As a result, the variable ${message} is "undefined". The code works by itself, but inside the if statement I can't see the output of the message. How to fix that?
Apparently, sendText = `${myMessage}`; is being executed before the message is received from the listener pyshell.
pyshell.on('message', function (message) {
console.log(message);
//decide here what you want to do with the message
});
Have a look at MDN docs to understand how the asynchronous code behaves.
Update:
The trick lies in waiting until the message is received then return it, a simple solution would be in wrapping the logic in asynchronouse function and trigger a callback once the message is received.
const { PythonShell } = require("python-shell");
var pyshell = new PythonShell(myPythonScriptPath);
function getShellMessage(callback) {
pyshell.on('message', function (message) {
console.log(message);
// end listener here pyshell.end() ?
callback(null, message);
});
// end the input stream and allow the process to exit
pyshell.end(function (err) {
if (err){
callback(err);
};
});
}
// the callback function will only get triggered upon receiving the message
getShellMessage(function(err, message) {
//message is ready
console.log(message)
});
message is a variable inside of pyshell.on() and it's obvious that message is undefined outside of this block. if you want to use the value of message, you have to declare a variable outside pyshell.on() and in pyshell.on() fill that with message value.
var message="";
pyshell.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message);
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am new to JavaScript. I don't get it why it prints the value undefined on the console before the correct id.
I am trying to return the inserted id yet I get an "undefined" on the return, but the console shows the correct id.
VisaFam.dbs.addFamily = function(nom) {
var db = VisaFam.dbs.db;
var family_id;
db.transaction(function(tx) {
tx.executeSql("INSERT INTO family (nom) VALUES (?)",
[nom],function(tx, results){
family_id= results.insertId; //i want to return this
console.log(results.insertId); // this prints the correct value
});
});
console.log(family_id); // this shows undefined
return family_id; // the return is thus "undefined"
}
I/O calls happens async in js and you should get returned value either from callbacks or promises:
VisaFam.dbs.addFamily = function(nom, callback) {
var db = VisaFam.dbs.db;
var family_id;
db.transaction(function(tx) {
tx.executeSql("INSERT INTO family (nom) VALUES (?)",
[nom],function(tx, results){
family_id= results.insertId; //i want to return this
console.log(results.insertId); // this prints the correct value
callback(results);
});
});
}
then call addFamily as:
addFamily(nom, function(response) {
//handle response
})
I don't have the full context of your program, but it seems that the db.transaction function is asynchronous. Because of this, the console.log() statement is running before the family_id variable has a value assigned to it.
To test this, you can change the line var family_id; to var family_id = "test";
Console should spit out "test" immediately.
To log the correct id you want, you need to move the console.log() call into the db.transaction function, which ensures the code will only execute after the value is set.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I am getting data from my database. This works.
However, there is something wrong with the flow of my code, I think it has to do with async: Why does facturasDotaciones[ ] (almost last line of code) resolve to undefined?
//npm sql DB access module (https://www.npmjs.com/package/mssql)
var sql = require('mssql');
//sql config object (username, password, etc)
var config = {
bla, bla, bla
}
function traerFacturasDotaciones(){
var request2 = new sql.Request(connection);
request2.execute('seleccionarFacturasCorreosDotaciones', function(err, response, returnValue) {
function peluquiarFacturas(facturas){
for(var i=0;i<facturas[0].length;i++){
facturas[0][i]["CO"]=facturas[0][i]["CO"].trim();
}
return facturas;
}
return peluquiarFacturas(response);
});
}
//get data from server and clean up
var connection = new sql.Connection(config, function(err) {
var request = new sql.Request(connection);
request.execute('seleccionarTiendas', function(err, tiendasRet, returnValue) {
var facturasDotaciones=[];
facturasDotaciones=traerFacturasDotaciones();
console.log("facturasDotaciones", facturasDotaciones);
});
});
traerFacturasDotaciones() doesnt return anything. It calls request2.execute, which calls a callback function passing the response.
One option is that you pass facturasDotaciones to traerFacturasDotaciones as argument and set the value inside that function, but even then it will be assigned in asncy manner. Go through request.execute method to see if it returns promise that you can wait on ?
The function traerFacturasDotaciones does not return anything. Note that the return statement is in a callback function given as second parameter to request2.execute. But that callback is executed asynchronously, and your function traerFacturasDotaciones ends before that callback is executed.
This question already has answers here:
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Closed 8 years ago.
I have this nodejs function, which is for inserting some data into db, and when it finishes inserting it should return 'success' or 'failure'.
This function is in the file insert.js
function insert (req,res) {
var d = req.body;
new dbModel({
name: d.dname,
desc: d.desc
}).save(false,function(err){
if (err){
return 'failure';
}else{
return 'success';
}
});
}
module.exports.insert = insert;
It inserts data into the db, but it doesnt return any value.
This is the route which invokes the above function and this is in the routes.js file.
router.post('/insert', function(req, res) {
var result = insert.insert(req,res);
res.render('insert',{title: 'insert',message: result});
});
Am I doing anything wrong or does this have something to do with async nature of nodejs.
Please help. Thanks.
EDIT
I tried as #Salehen Rahman said in the answers below, but the page isn't rendering and the browser keeps on waiting for reply from the server and i tried to log the value of result inside the callback function and again no output, it seems the code inside the callback function is not running. I checked the db and data has been inserted successfully.
That dbModel#save method is asynchronous, and so, the return keyword will only return to the inner the anonymous function. You want to use callbacks, instead. Also remove false from the save method. It can have only callback function as a parameter.
So, your insert function will look like this:
function insert (req, res, callback) {
var d = req.body;
new dbModel({
name: d.dname,
desc: d.desc
}).save(function(err){
if (err){
// Instead of return, you call the callback
callback(null, 'failure');
}else{
// Instead of return, you call the callback
callback(null, 'success');
}
});
}
module.exports.insert = insert;
And your route function will look like this:
router.post('/insert', function(req, res) {
insert.insert(req, res, function (err, result) {
res.render('insert',{title: 'insert', message: result});
});
});
Ideally, though, whenever an inner callback returns an error, you should also call your callback with the error, without any result; absent an error, and at the presence of a successful function call, you set the first parameter to null, and the second parameter to your result.
Typically, the first parameter of the callback call represents an error, where as the second parameter represents your result.
As a reference, you may want to read up on Node.js' callback pattern.
This question already has answers here:
Synchronous query to Web SQL Database
(2 answers)
Closed 8 years ago.
I'm trying to pass the result from an SQLite SELECT to the var res and show it but in the alert I get "undefined". How to correctly return it?
function read(key){
app.db.transaction(function(tx) {
tx.executeSql('SELECT value FROM MyTable WHERE key = ?',
[key],
function(tx, results)
{
return results.rows.item(0)['value']
},
app.onError
);
return;
});
return;
}
res=read("pipi")
alert(res);
You cannot return a value from an asynchronous function. You need to either pass a function that will execute with the results of the async function OR use a global variable to hold the results.
res=read("pipi") // will always return undefined
you can declare a global variable and a global function.
resultSelect = "";
function alertResultSelect(result){
alert(result);
}
then in your function(tx, results) code add
function(tx, results)
{
//Assign the results to the global variable.
resultSelect = results.rows.item(0)['value'];
// OR call the global function
alertResultSelect(results.rows.item(0)['value']);
}