Why is my global variable undefined? [duplicate] - javascript

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.

Related

Console.log prints the data but function doesn't return data [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I'm trying to achieve the URL tracking with below custom made script that extracts the json data that is in array and prints in console.log successfully
function redirecTrace(url){
var urltoprint = [];
fetch("https://redirecttraceservice.com/api/v1/header-checker?initialURL="+url, {
method: "POST"
})
.then(response => response.text()).then((response) => {
var regex = new RegExp(/(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^"\s]{2,}) - Response 20[01]/);
if(response.match(regex)){
urltoprint = response.match(regex);
console.log(encodeURIComponent(urltoprint[1]));
return ("This is from return: " + urltoprint[1]);
}else{
console.log("Destination URL Not Found");
return "Destination URL Not Found";
}
});
}
So above code prints data in console.log but doesn't returns the data! it always says undefined?
Your return is inside an arrow function inside a promise chain inside the redirecTrace function. So it is returning the value from the inner arrow function, but that does not apply to the outer function. What you want is to also return the promise (put return before the fetch() call). Then you can do this:
redirecTrace(url).then(returnValue => {
// Do something with the returned value
});

returning data nested inside ajax callback [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
im trying to get data from an ajax function to my actual app but i cant seem to pass the data outside of the function, ive read other questions and tried their recommendation but it doesnt seem to be working because its not waiting for ajax to finish loading before trying to return the data,
im trying to return uid so that i can do something like
user = getUserID('test');
instead of
getUserID('user', function(id){ console.log(id); });
because i am assigning the returned data to a variable
getUserID = function(user, cb) {
var uid;
$.ajax({
type: "GET",
url: "/user_comment.php",
data: {
user: user
},
success: function(result) {
if (result) {
uid = /name="recipient_id" value="(.*)"/g.exec(result)[1];
console.log('1 ' + uid);
if(cb) {
try {
cb(null, uid);
} catch(e) { cb(e); }
}
} else {
console.log("ERROR!! - No data returned !")
}
}
});
console.log('2 ' + uid);
return uid;
},
all it does right now is
2 undefined
1 5511194
2 undefined
1 1462473
2 undefined
1 5469682
so it is not setting the variable
Your code is returning the value of "uid" before any value is applied to it. You can see that your variable is set in "success" callback. This means that this callback will be called only after the asynchronous call is done. Your "getUserID" function will end AND the "return" statement will be executed BEFORE the callback. Play with your code in the debugger, you'll see what's actually going on. So what you should do is use the returned value in the "success" callback instead of the returned value from "getUserID". Like this:
getUserID('test', function(uid){
... do your stuff here => uid is defined and has the value you're looking for
});
But just don't try to do something like:
var uid = getUserID('test');
... things and stuff

async JS: why does my variable resolve to undefined? [duplicate]

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.

Javascript not assign to variable [duplicate]

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

How to return a result from a SQLite SELECT? [duplicate]

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']);
}

Categories