Save result to variable? - mysql

So I have been developing a note taking app, and I am having some trouble with displaying the username! Normally you would get a result like this:
con.query('SELECT someVariable FROM someColumn', function (result) {
console.log(result)
})
But I would like to save the result to a variable like this:
var variable = '';
con.query('SELECT someVariable FROM someColumn', function (result) {
variable = result
})
console.log("Here is some data: " + variable)
But that obviously wouldn't work. So how can I do this???
The point
How would I save a mySQL result to a variable, so it can be used later in my code? Also Im not an experienced developer so you might have to do a bit more explaining that usual, thanks.

If you're new to Node and/or JavaScript then you've just stumbled on one of the major problems of asynchronous programming. Here's your code as the JavaScript runtime sees it:
// Declare variable
var variable = '';
var callback = function(result) {
variable = result;
};
// This code runs right away
con.query('SELECT someVariable FROM someColumn', callback);
// Then this code runs
console.log("Here is some data: " + variable);
// Then, a thousand years later (from a CPU's perspective) this callback executes
callback(result);
You can see you're jumping the gun here. You can't depend on any behaviour until the callback has run, or in other words, you need to put any dependent behaviour inside the callback.
Since it's 2020 you can also do this with async and await if you're using a Promise-capable library. Your code could look like:
// Assign variable to the result of the query call, waiting as long as necessary
let variable = await con.query('SELECT someVariable FROM someColumn');
console.log("Here is some data: " + variable);
This will be properly sequenced.

Related

Node.js trying to use async/await to get data from a mysql select before using the variable

I need to catch some data by a mysql query, and use the result to build up and email message with its results with node.
I put the code inside a function, but the call to the query appear to still be async, as the result is never given back before the end of the function, and the returning variable is alwasy empty.
Tried different approach with async/await but still the execution seems async
In my following code is just get in the console log up to the step 3, the step 4 is mde no matter what I try to do at the end of the function call
async function querydb (utente){
console.log("sono in querydb");
var messageHTMLAllegati="";
var risultatoquery;
console.log("step 1");
var connection = mysql.createConnection({
host : process.env.IP_address,
user : process.env.nome_utente,
password : process.env.password,
port : process.env.port,
database : process.env.DB,
});
console.log("step 2");
const query = util.promisify(connection.query).bind(connection);
(async () => {
try {
console.log("step 3");
var result = await query('SELECT Link FROM Link_Foto where ID_Utente="' + utente + '"');
var i = result.length;
console.log("step 4");
var j ;
for (j=0; j < i; j++) {
messageHTMLAllegati +='Immagine ' + (j+1)+ '<BR>';
console.log("print the link found in the DB and added to the text to be printed"+result[j].Link);
}
} finally {
connection.end();
}
})()
return messageHTMLAllegati;
}
I do expect the final variable "messageHTMLAllegati" to contain some text plus the query fields needed, but it get always empty. In the log I see though that the variable is filled up, but only after that the function is returned, therefore the text used to put the email together is empty from the DB section
async/await method only works when await functions is a promise. functions like 'query' in mysql are using a callback function to get the result. So if you want to use it with async/await method you should use it in another function and get the result in its callback function as a promise like this:
function query_promise(q_string){
return new Promise((resolve, reject)=>{
query(q_string,(err, result)=>{
if(err) return reject(err);
resolve(result);
});
});
}
then in your code:
var result = await query_promise('SELECT Link FROM Link_Foto where ID_Utente="' + utente + '"');

How can i return value that is inside a query function?

I have just started coding Node. I have a function that name is "add" and there is a mysql query inside the function.
I can't return "row" variable which is inside of the query function.
How can i do this?
Broadcast.prototype.add = function (id) {
var broadcast;
mysql.query("SELECT * from Table WHERE Id='" + id + "'", function(err, row) {
if(!err) {
return row; //it didn't work
broadcast = row; //it didn't work
}
});
};
The code after the return statement (broadcast = row;) is not excecuted.
You should make them switch position if you want to assign the value of row to broadcast. In your comments however you've written that you want the results to be added to the array broadcast. That's why in the provided awnser you'll find it is an array and the row value is added to it.
Also because it runs in async you will need some callback function when the value has been added. Otherwise logging the broadcast array to fast may results in a 'still' empty array.
Broadcast.prototype.broadcast = [];
Broadcast.prototype.add = function (id,cb) {
// Use self or bind the function(err,row) to Broadcast instead so you can use a normal this inside that function as well
var self = this;
mysql.query("SELECT * FROM Table WHERE Id='" + id + "'", function(err, row){
// Check for errors
if (err) {return console.log(err);}
// Add the value of row to the broadcast array
self.broadcast.push(row);
// Run the callback function
cb();
});
};
var broadcast = new Broadcast();
broadcast.add(id, callbackFunction = function(){
// Here broadcast should have a value
console.log(broadcast.broadcast);
});
// Here broadcast is likely not to have a value yet because mysql.query is probably executed in async.
console.log(broadcast.broadcast);

nightwatch.js return value from function outside a test

I have trouble moving certain code outside a test into a function that needs to return a value.
Here is part of my code for the test file
function getCountOfTopics(browser){
var count;
browser.getText('#sumTopics',
function(result){
count = result.value;
console.log(result.value);
}
);
return count;
};
module.exports = {
'Create article' : function(browser){
var noOfThreadsByInlineCode, noOfThreadsByFunction;
browser.getText('#sumTopics',
function(result){
noOfThreadsByInlineCode = result.value;
}
);
noOfThreadsByFunction = getCountOfTopics(browser);
browser.end();
}
}
Now, the variable noOfThreadsByInlineCode indeed gets the value in the DOM, but the variable noOfThreadsByFunction is undefined. The console does indeed print the correct value, so the function does get the correct value out of the DOM.
I would appreciate help in updating the function so that I do get the value returned.
One word answer is Asynchronisity. The code doesn't wait for your callback to get complete, thats what the feature of Node JS is.
If you are in desperately in need for the content inside of the callback you can write this variable into a file and then access it anywhere you want inside your code. Here's a bit of a workaround:
Save something in a file:
var fs = require('fs');
iThrowACallBack(function(response){
fs.writeFile('youCanSaveData.txt', this.response, function(err) {
if (err) throw err;
console.log('Saved!');
browser.pause(5000);
});
});
Access it somewhere else:
iAccessThefile(){
response = fs.readFileSync('youCanSaveData.txt').toString('utf-8');
}
Hope it helps.
You return variable 'count' outside the callback,that is why.You can take a look this topic How to return value from an asynchronous callback function?
function getCountOfTopics(browser){
var count;
browser.getText('#sumTopics',
function(result){
count = result.value;
console.log(result.value);
/// result.value is available in this callback.
}
);
What do you want to do with the 'value'?
ps:do not remember custom_command.I think it is very helpful for this issue.

Gulp task - unable to set variable value

I'm using git-rev,gulp-header and run-sequence and trying to add some info - as well as - git commit number automatically to app.js file during building process.
here's the code I have so far:
var runSequence = require('gulp-run-sequence');
var git = require('git-rev');
var header = require('gulp-header');
var pkg = require('./info.json');
var paths = {addHeader: ['./www/js/app.js'], ...}
var commit, timestamp;
function getGitInfo() {
git.short(function (str) {
commit = str;
console.log(str);
});
};
var banner = ['"commit":"' + commit + '",',
'"timestamp":"' + timestamp + '",',
'"appVersion":"<%= pkg.appVersion %>",',
'"appReleaseDate":"<%= pkg.appReleaseDate %>"',
'};\n',
''].join('\n');
gulp.task('get-git-info', getGitInfo());
gulp.task('add-header', function () {
return gulp.src(paths.addHeader)
.pipe(header(banner, {pkg: pkg}))
.pipe(gulp.dest('./www-dev/js/'))
});
gulp.task('build', function (){
runSequence('get-git-info','add-header');
})
the console result is right, I have the commit number, but in app.js all I get is undefined:
aboutPage={
"appVersion":"5.0.0",
"appReleaseDate":"10/02/2016",
"commit":"undefined",
"timestamp":"undefined"
};
I am talking about commit, and NOT timestamp. I'm going to worry about timestamp later.
Any idea what am I doing wrong here?
thanks
There are a couple of things wrong with your Gulpfile:
Your banner variable is initialized before any of your tasks are even defined, let alone have been executed. That means that commit is still undefined when you initialize banner.
gulp.task expects a function as the task body. However the task body for get-git-info in your Gulpfile is getGitInfo(). That means you execute the getGitInfo function and assign the return value of that function call as the task body of get-git-info. Which in your case is undefined.
Even if you had assigned the getGitInfo function itself as the task body (instead of its return value), it still wouldn't work because git.short() is asynchronous. That means that get-git-info returns and add-header is run before your callback function to git.short() is called with the commit-id.
Here's a solution that addresses all three of these problems:
function banner() {
return [
'"commit":"' + commit + '",',
'"timestamp":"' + timestamp + '",',
'"appVersion":"<%= pkg.appVersion %>",',
'"appReleaseDate":"<%= pkg.appReleaseDate %>"',
'};\n',
''
].join('\n');
}
gulp.task('get-git-info', function(done) {
git.short(function (str) {
commit = str;
console.log(str);
done();
});
});
gulp.task('add-header', function () {
return gulp.src(paths.addHeader)
.pipe(header(banner(), {pkg: pkg}))
.pipe(gulp.dest('./www-dev/js/'))
});
banner is now a function so the commit variable isn't accessed until it has been initialized.
getGitInfo is gone. Instead an anonymous function is used as the task body for get-git-info, so it's dead obvious that we are in fact assigning a function here.
The anonymous function accepts a callback done which is called once the commit-id is available. This signals to gulp that get-git-info is finished and that runSequence can proceed with the add-header task.

Trying to interpret the Node-Neo4j API

I'm pretty new to coding so forgive me if my code is unreadable or my question simplistic.
I am trying to create a little server application that (amongst other things) displays the properties of a neo4j node. I am using node.js, Express and Aseem Kishore's Node-Neo4j REST API client, the documentation for which can be found here.
My question stems from my inability to fetch the properties of nodes and paths. I can return a node or path, but they seem to be full of objects with which I cannot interact. I poured through the API documents looking for some examples of how particular methods are called but I found nothing.
Ive been trying to call the #toJSON method like, "db.toJSON(neoNode);" but it tells me that db does not contain that method. I've also tried, "var x = neoNode.data" but it returns undefined.
Could someone please help me figure this out?
//This file accepts POST data to the "queryanode" module
//and sends it to "talkToNeo" which queries the neo4j database.
//The results are sent to "resultants" where they are posted to
//a Jade view. Unfortuantly, the data comes out looking like
// [object Object] or a huge long string, or simply undefined.
var neo4j = require('neo4j');
var db = new neo4j.GraphDatabase('http://localhost:7474');
function resultants(neoNode, res){
// if I console.log(neoNode) here, I now get the 4 digit integer
// that Neo4j uses as handles for nodes.
console.log("second call of neoNode" + neoNode);
var alpha = neoNode.data; //this just doesn't work
console.log("alpha is: " +alpha); //returns undefined
var beta = JSON.stringify(alpha);
console.log("logging the node: ");
console.log(beta);// still undefined
res.render("results",{path: beta});
res.end('end');
}
function talkToNeo (reqnode, res) {
var params = {
};
var query = [
'MATCH (a {xml_id:"'+ reqnode +'"})',
'RETURN (a)'
].join('\n');
console.log(query);
db.query(query, params, function (err, results) {
if (err) throw err;
var neoNode = results.map(function (result){
return result['a']; //this returns a long string, looks like an array,
//but the values cannot be fetched out
});
console.log("this is the value of neoNode");
console.log(neoNode);
resultants(neoNode, res);
});
};
exports.queryanode = function (req, res) {
console.log('queryanode called');
if (req.method =='POST'){
var reqnode = req.body.node; //this works as it should, the neo4j query passes in
talkToNeo(reqnode, res) //the right value.
}
}
EDIT
Hey, I just wanted to answer my own question for anybody googling node, neo4j, data, or "How do I get neo4j properties?"
The gigantic object from neo4j, that when you stringified it you got all the "http://localhost:7474/db/data/node/7056/whatever" urls everywhere, that's JSON. You can query it with its own notation. You can set a variable to the value of a property like this:
var alpha = unfilteredResult[0]["nodes(p)"][i]._data.data;
Dealing with this JSON can be difficult. If you're anything like me, the object is way more complex than any internet example can prepare you for. You can see the structure by putting it through a JSON Viewer, but the important thing is that sometimes there's an extra, unnamed top layer to the object. That's why we call the zeroth layer with square bracket notation as such: unfilteredResult[0] The rest of the line mixes square and dot notation but it works. This is the final code for a function that calculates the shortest path between two nodes and loops through it. The final variables are passed into a Jade view.
function talkToNeo (nodeone, nodetwo, res) {
var params = {
};
var query = [
'MATCH (a {xml_id:"'+ nodeone +'"}),(b {xml_id:"' + nodetwo + '"}),',
'p = shortestPath((a)-[*..15]-(b))',
'RETURN nodes(p), p'
].join('\n');
console.log("logging the query" +query);
db.query(query, params, function (err, results) {
if (err) throw err;
var unfilteredResult = results;
var neoPath = "Here are all the nodes that make up this path: ";
for( i=0; i<unfilteredResult[0]["nodes(p)"].length; i++) {
neoPath += JSON.stringify(unfilteredResult[0]['nodes(p)'][i]._data.data);
}
var pathLength = unfilteredResult[0].p._length;
console.log("final result" + (neoPath));
res.render("results",{path: neoPath, pathLength: pathLength});
res.end('end');
});
};
I would recommend that you look at the sample application, which we updated for Neo4j 2.0
Which uses Cypher to load the data and Node-labels to model the Javascript types.
You can find it here: https://github.com/neo4j-contrib/node-neo4j-template
Please ask more questions after looking at this.