How to properly return a result from mysql with Node?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
In the code
var stuff_i_want = '';
stuff_i_want = get_info(parm);
And the function get_info:
get_info(data){
var sql = "SELECT a from b where info = data"
connection.query(sql, function(err, results){
if (err){
throw err;
}
console.log(results[0].objid); // good
stuff_i_want = results[0].objid; // Scope is larger than function
console.log(stuff_i_want); // Yep. Value assigned..
}
in the larger scope
stuff_i_want = null
What am i missing regarding returning mysql data and assigning it to a variable?
============ New code per Alex suggestion
var parent_id = '';
get_info(data, cb){
var sql = "SELECT a from b where info = data"
connection.query(sql, function(err, results){
if (err){
throw err;
}
return cb(results[0].objid); // Scope is larger than function
}
==== New Code in Use
get_data(parent_recording, function(result){
parent_id = result;
console.log("Parent ID: " + parent_id); // Data is delivered
});
However
console.log("Parent ID: " + parent_id);
In the scope outside the function parent_id is null
node.js
add a comment |
In the code
var stuff_i_want = '';
stuff_i_want = get_info(parm);
And the function get_info:
get_info(data){
var sql = "SELECT a from b where info = data"
connection.query(sql, function(err, results){
if (err){
throw err;
}
console.log(results[0].objid); // good
stuff_i_want = results[0].objid; // Scope is larger than function
console.log(stuff_i_want); // Yep. Value assigned..
}
in the larger scope
stuff_i_want = null
What am i missing regarding returning mysql data and assigning it to a variable?
============ New code per Alex suggestion
var parent_id = '';
get_info(data, cb){
var sql = "SELECT a from b where info = data"
connection.query(sql, function(err, results){
if (err){
throw err;
}
return cb(results[0].objid); // Scope is larger than function
}
==== New Code in Use
get_data(parent_recording, function(result){
parent_id = result;
console.log("Parent ID: " + parent_id); // Data is delivered
});
However
console.log("Parent ID: " + parent_id);
In the scope outside the function parent_id is null
node.js
add a comment |
In the code
var stuff_i_want = '';
stuff_i_want = get_info(parm);
And the function get_info:
get_info(data){
var sql = "SELECT a from b where info = data"
connection.query(sql, function(err, results){
if (err){
throw err;
}
console.log(results[0].objid); // good
stuff_i_want = results[0].objid; // Scope is larger than function
console.log(stuff_i_want); // Yep. Value assigned..
}
in the larger scope
stuff_i_want = null
What am i missing regarding returning mysql data and assigning it to a variable?
============ New code per Alex suggestion
var parent_id = '';
get_info(data, cb){
var sql = "SELECT a from b where info = data"
connection.query(sql, function(err, results){
if (err){
throw err;
}
return cb(results[0].objid); // Scope is larger than function
}
==== New Code in Use
get_data(parent_recording, function(result){
parent_id = result;
console.log("Parent ID: " + parent_id); // Data is delivered
});
However
console.log("Parent ID: " + parent_id);
In the scope outside the function parent_id is null
node.js
In the code
var stuff_i_want = '';
stuff_i_want = get_info(parm);
And the function get_info:
get_info(data){
var sql = "SELECT a from b where info = data"
connection.query(sql, function(err, results){
if (err){
throw err;
}
console.log(results[0].objid); // good
stuff_i_want = results[0].objid; // Scope is larger than function
console.log(stuff_i_want); // Yep. Value assigned..
}
in the larger scope
stuff_i_want = null
What am i missing regarding returning mysql data and assigning it to a variable?
============ New code per Alex suggestion
var parent_id = '';
get_info(data, cb){
var sql = "SELECT a from b where info = data"
connection.query(sql, function(err, results){
if (err){
throw err;
}
return cb(results[0].objid); // Scope is larger than function
}
==== New Code in Use
get_data(parent_recording, function(result){
parent_id = result;
console.log("Parent ID: " + parent_id); // Data is delivered
});
However
console.log("Parent ID: " + parent_id);
In the scope outside the function parent_id is null
node.js
node.js
edited Aug 7 '15 at 11:12
Ken Ingram
asked Aug 7 '15 at 10:32
Ken IngramKen Ingram
56351431
56351431
add a comment |
add a comment |
4 Answers
4
active
oldest
votes
You're going to need to get your head around asynchronous calls and callbacks with javascript, this isn't c# / php etc...
Here's an example using your code:
function get_info(data, callback){
var sql = "SELECT a from b where info = data";
connection.query(sql, function(err, results){
if (err){
throw err;
}
console.log(results[0].objid); // good
stuff_i_want = results[0].objid; // Scope is larger than function
return callback(results[0].objid);
}
}
//usage
var stuff_i_want = '';
get_info(parm, function(result){
stuff_i_want = result;
//rest of your code goes in here
});
When you call get_info
this in turn calls connection.query, which takes a callback (that's what function(err, results)
is
The scope is then passed to this callback, and so on.
Welcome to javascript callback hell...
It's easy when you get the hang of it, just takes a bit of getting used to, coming from something like C#
1
wow. callback hell is right. thanks. this may be the simplest explanation so far. I'll give it a try...
– Ken Ingram
Aug 7 '15 at 10:48
once you get the hang of it, try something likeasync'js
- but understand the inner workings first!
– Alex
Aug 7 '15 at 10:49
I followed your example but I still appear to be getting nothing back from my query, though the query is perfectly fine. Nothing comes out of the mysql.query. I'm flummoxed.
– Ken Ingram
Aug 7 '15 at 10:57
which bit? where is nothing coming out?
– Alex
Aug 7 '15 at 10:58
5
thanks man, 2 hours later finally found something that makes sense. Coming from PHP background gotta say that JS is a hard language to like
– Robert Sinclair
Jun 27 '18 at 1:01
|
show 5 more comments
I guess what you really want to do here is returning a Promise object with the results. This way you can deal with the async operation of retrieving data from the DBMS: when you have the results, you make use of the Promise resolve function to somehow "return the value" / "resolve the promise".
Here's an example:
getEmployeeNames = function(){
return new Promise(function(resolve, reject){
connection.query(
"SELECT Name, Surname FROM Employee",
function(err, rows){
if(rows === undefined){
reject(new Error("Error rows is undefined"));
}else{
resolve(rows);
}
}
)}
)}
On the caller side, you use the then
function to manage fulfillment, and the catch
function to manage rejection.
Here's an example that makes use of the code above:
getEmployeeNames()
.then(function(results){
render(results)
})
.catch(function(err){
console.log("Promise rejection error: "+err);
})
At this point you can set up the view for your results (which are indeed returned as an array of objects):
render = function(results){ for (var i in results) console.log(results[i].Name) }
Edit
I'm adding a basic example on how to return HTML content with the results, which is a more typical scenario for Node. Just use the then
function of the promise to set the HTTP response, and open your browser at http://localhost:3001
require('http').createServer( function(req, res){
if(req.method == 'GET'){
if(req.url == '/'){
res.setHeader('Content-type', 'text/html');
getEmployeeNames()
.then(function(results){
html = "<h2>"+results.length+" employees found</h2>"
html += "<ul>"
for (var i in results) html += "<li>" + results[i].Name + " " +results[i].Surname + "</li>";
html += "</ul>"
res.end(html);
})
.catch(function(err){
console.log("Promise rejection error: "+err);
res.end("<h1>ERROR</h1>")
})
}
}
}).listen(3001)
Cool. I've done this with another script, but when I try to move from console.log of results to putting them in an array, I get nothing. What's the solution when I don't want it going to console?
– Ken Ingram
Jun 27 '18 at 22:22
@KenIngram you should post your code: what are you trying to do? Therender
function I posted gets the array as parameter, soresults
is your array of objects. If you print it directly you'll get something like[ RowDataPacket { Name: 'James' }, RowDataPacket { Name: 'Mary' } ]
. You can also access array properties likeresults.length
.
– gtugnolo
Jun 29 '18 at 9:20
I was able to get some help on the Promises. Now that I understand it, your example makes complete sense.
– Ken Ingram
Jul 29 '18 at 20:11
add a comment |
This was a situation where I was inserting new records to a child table and needed the prent record key, based only on a name.
This was a good example of understanding the asynchronous nature of node.
I needed to wrap the all the code affecting the child records inside the call to find the parent record id.
I was approaching this from a sequential (PHP, JAVA) perspective, which was all wrong.
add a comment |
Easier if you send in a promise to be resolved
e.g
function get_info(data, promise){
var sql = "SELECT a from b where info = data";
connection.query(sql, function(err, results){
if (err){
throw err;
}
console.log(results[0].objid); // good
stuff_i_want = results[0].objid; // Scope is larger than function
promise.resolve(results[0].objid);
}
}
This way Node.js will stay fast because it's busy doing other things while your promise is waiting to be resolved
Thanks. I've been trying to implement Promises. I am stuck at converting the returned promise into usable data. I understand the concept, however, how to complete the technical implementation is eluding me.
– Ken Ingram
Sep 13 '17 at 22:08
1
db.findOne(272).then((user) => { console.log("Find user in location strategy", user[0]); return done(null, user[0]); }).catch(error => { return done(err); });
– Epirocks
Sep 13 '17 at 23:34
I keep looking at this. It's an answer, but it assumes I understand how to make sense of it. I figured out Promises, but his snippet never actually helped. I needed a simpler breakdown. Neurodiverse.
– Ken Ingram
Dec 28 '18 at 4:22
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f31875621%2fhow-to-properly-return-a-result-from-mysql-with-node%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
You're going to need to get your head around asynchronous calls and callbacks with javascript, this isn't c# / php etc...
Here's an example using your code:
function get_info(data, callback){
var sql = "SELECT a from b where info = data";
connection.query(sql, function(err, results){
if (err){
throw err;
}
console.log(results[0].objid); // good
stuff_i_want = results[0].objid; // Scope is larger than function
return callback(results[0].objid);
}
}
//usage
var stuff_i_want = '';
get_info(parm, function(result){
stuff_i_want = result;
//rest of your code goes in here
});
When you call get_info
this in turn calls connection.query, which takes a callback (that's what function(err, results)
is
The scope is then passed to this callback, and so on.
Welcome to javascript callback hell...
It's easy when you get the hang of it, just takes a bit of getting used to, coming from something like C#
1
wow. callback hell is right. thanks. this may be the simplest explanation so far. I'll give it a try...
– Ken Ingram
Aug 7 '15 at 10:48
once you get the hang of it, try something likeasync'js
- but understand the inner workings first!
– Alex
Aug 7 '15 at 10:49
I followed your example but I still appear to be getting nothing back from my query, though the query is perfectly fine. Nothing comes out of the mysql.query. I'm flummoxed.
– Ken Ingram
Aug 7 '15 at 10:57
which bit? where is nothing coming out?
– Alex
Aug 7 '15 at 10:58
5
thanks man, 2 hours later finally found something that makes sense. Coming from PHP background gotta say that JS is a hard language to like
– Robert Sinclair
Jun 27 '18 at 1:01
|
show 5 more comments
You're going to need to get your head around asynchronous calls and callbacks with javascript, this isn't c# / php etc...
Here's an example using your code:
function get_info(data, callback){
var sql = "SELECT a from b where info = data";
connection.query(sql, function(err, results){
if (err){
throw err;
}
console.log(results[0].objid); // good
stuff_i_want = results[0].objid; // Scope is larger than function
return callback(results[0].objid);
}
}
//usage
var stuff_i_want = '';
get_info(parm, function(result){
stuff_i_want = result;
//rest of your code goes in here
});
When you call get_info
this in turn calls connection.query, which takes a callback (that's what function(err, results)
is
The scope is then passed to this callback, and so on.
Welcome to javascript callback hell...
It's easy when you get the hang of it, just takes a bit of getting used to, coming from something like C#
1
wow. callback hell is right. thanks. this may be the simplest explanation so far. I'll give it a try...
– Ken Ingram
Aug 7 '15 at 10:48
once you get the hang of it, try something likeasync'js
- but understand the inner workings first!
– Alex
Aug 7 '15 at 10:49
I followed your example but I still appear to be getting nothing back from my query, though the query is perfectly fine. Nothing comes out of the mysql.query. I'm flummoxed.
– Ken Ingram
Aug 7 '15 at 10:57
which bit? where is nothing coming out?
– Alex
Aug 7 '15 at 10:58
5
thanks man, 2 hours later finally found something that makes sense. Coming from PHP background gotta say that JS is a hard language to like
– Robert Sinclair
Jun 27 '18 at 1:01
|
show 5 more comments
You're going to need to get your head around asynchronous calls and callbacks with javascript, this isn't c# / php etc...
Here's an example using your code:
function get_info(data, callback){
var sql = "SELECT a from b where info = data";
connection.query(sql, function(err, results){
if (err){
throw err;
}
console.log(results[0].objid); // good
stuff_i_want = results[0].objid; // Scope is larger than function
return callback(results[0].objid);
}
}
//usage
var stuff_i_want = '';
get_info(parm, function(result){
stuff_i_want = result;
//rest of your code goes in here
});
When you call get_info
this in turn calls connection.query, which takes a callback (that's what function(err, results)
is
The scope is then passed to this callback, and so on.
Welcome to javascript callback hell...
It's easy when you get the hang of it, just takes a bit of getting used to, coming from something like C#
You're going to need to get your head around asynchronous calls and callbacks with javascript, this isn't c# / php etc...
Here's an example using your code:
function get_info(data, callback){
var sql = "SELECT a from b where info = data";
connection.query(sql, function(err, results){
if (err){
throw err;
}
console.log(results[0].objid); // good
stuff_i_want = results[0].objid; // Scope is larger than function
return callback(results[0].objid);
}
}
//usage
var stuff_i_want = '';
get_info(parm, function(result){
stuff_i_want = result;
//rest of your code goes in here
});
When you call get_info
this in turn calls connection.query, which takes a callback (that's what function(err, results)
is
The scope is then passed to this callback, and so on.
Welcome to javascript callback hell...
It's easy when you get the hang of it, just takes a bit of getting used to, coming from something like C#
answered Aug 7 '15 at 10:43
AlexAlex
20.9k38162289
20.9k38162289
1
wow. callback hell is right. thanks. this may be the simplest explanation so far. I'll give it a try...
– Ken Ingram
Aug 7 '15 at 10:48
once you get the hang of it, try something likeasync'js
- but understand the inner workings first!
– Alex
Aug 7 '15 at 10:49
I followed your example but I still appear to be getting nothing back from my query, though the query is perfectly fine. Nothing comes out of the mysql.query. I'm flummoxed.
– Ken Ingram
Aug 7 '15 at 10:57
which bit? where is nothing coming out?
– Alex
Aug 7 '15 at 10:58
5
thanks man, 2 hours later finally found something that makes sense. Coming from PHP background gotta say that JS is a hard language to like
– Robert Sinclair
Jun 27 '18 at 1:01
|
show 5 more comments
1
wow. callback hell is right. thanks. this may be the simplest explanation so far. I'll give it a try...
– Ken Ingram
Aug 7 '15 at 10:48
once you get the hang of it, try something likeasync'js
- but understand the inner workings first!
– Alex
Aug 7 '15 at 10:49
I followed your example but I still appear to be getting nothing back from my query, though the query is perfectly fine. Nothing comes out of the mysql.query. I'm flummoxed.
– Ken Ingram
Aug 7 '15 at 10:57
which bit? where is nothing coming out?
– Alex
Aug 7 '15 at 10:58
5
thanks man, 2 hours later finally found something that makes sense. Coming from PHP background gotta say that JS is a hard language to like
– Robert Sinclair
Jun 27 '18 at 1:01
1
1
wow. callback hell is right. thanks. this may be the simplest explanation so far. I'll give it a try...
– Ken Ingram
Aug 7 '15 at 10:48
wow. callback hell is right. thanks. this may be the simplest explanation so far. I'll give it a try...
– Ken Ingram
Aug 7 '15 at 10:48
once you get the hang of it, try something like
async'js
- but understand the inner workings first!– Alex
Aug 7 '15 at 10:49
once you get the hang of it, try something like
async'js
- but understand the inner workings first!– Alex
Aug 7 '15 at 10:49
I followed your example but I still appear to be getting nothing back from my query, though the query is perfectly fine. Nothing comes out of the mysql.query. I'm flummoxed.
– Ken Ingram
Aug 7 '15 at 10:57
I followed your example but I still appear to be getting nothing back from my query, though the query is perfectly fine. Nothing comes out of the mysql.query. I'm flummoxed.
– Ken Ingram
Aug 7 '15 at 10:57
which bit? where is nothing coming out?
– Alex
Aug 7 '15 at 10:58
which bit? where is nothing coming out?
– Alex
Aug 7 '15 at 10:58
5
5
thanks man, 2 hours later finally found something that makes sense. Coming from PHP background gotta say that JS is a hard language to like
– Robert Sinclair
Jun 27 '18 at 1:01
thanks man, 2 hours later finally found something that makes sense. Coming from PHP background gotta say that JS is a hard language to like
– Robert Sinclair
Jun 27 '18 at 1:01
|
show 5 more comments
I guess what you really want to do here is returning a Promise object with the results. This way you can deal with the async operation of retrieving data from the DBMS: when you have the results, you make use of the Promise resolve function to somehow "return the value" / "resolve the promise".
Here's an example:
getEmployeeNames = function(){
return new Promise(function(resolve, reject){
connection.query(
"SELECT Name, Surname FROM Employee",
function(err, rows){
if(rows === undefined){
reject(new Error("Error rows is undefined"));
}else{
resolve(rows);
}
}
)}
)}
On the caller side, you use the then
function to manage fulfillment, and the catch
function to manage rejection.
Here's an example that makes use of the code above:
getEmployeeNames()
.then(function(results){
render(results)
})
.catch(function(err){
console.log("Promise rejection error: "+err);
})
At this point you can set up the view for your results (which are indeed returned as an array of objects):
render = function(results){ for (var i in results) console.log(results[i].Name) }
Edit
I'm adding a basic example on how to return HTML content with the results, which is a more typical scenario for Node. Just use the then
function of the promise to set the HTTP response, and open your browser at http://localhost:3001
require('http').createServer( function(req, res){
if(req.method == 'GET'){
if(req.url == '/'){
res.setHeader('Content-type', 'text/html');
getEmployeeNames()
.then(function(results){
html = "<h2>"+results.length+" employees found</h2>"
html += "<ul>"
for (var i in results) html += "<li>" + results[i].Name + " " +results[i].Surname + "</li>";
html += "</ul>"
res.end(html);
})
.catch(function(err){
console.log("Promise rejection error: "+err);
res.end("<h1>ERROR</h1>")
})
}
}
}).listen(3001)
Cool. I've done this with another script, but when I try to move from console.log of results to putting them in an array, I get nothing. What's the solution when I don't want it going to console?
– Ken Ingram
Jun 27 '18 at 22:22
@KenIngram you should post your code: what are you trying to do? Therender
function I posted gets the array as parameter, soresults
is your array of objects. If you print it directly you'll get something like[ RowDataPacket { Name: 'James' }, RowDataPacket { Name: 'Mary' } ]
. You can also access array properties likeresults.length
.
– gtugnolo
Jun 29 '18 at 9:20
I was able to get some help on the Promises. Now that I understand it, your example makes complete sense.
– Ken Ingram
Jul 29 '18 at 20:11
add a comment |
I guess what you really want to do here is returning a Promise object with the results. This way you can deal with the async operation of retrieving data from the DBMS: when you have the results, you make use of the Promise resolve function to somehow "return the value" / "resolve the promise".
Here's an example:
getEmployeeNames = function(){
return new Promise(function(resolve, reject){
connection.query(
"SELECT Name, Surname FROM Employee",
function(err, rows){
if(rows === undefined){
reject(new Error("Error rows is undefined"));
}else{
resolve(rows);
}
}
)}
)}
On the caller side, you use the then
function to manage fulfillment, and the catch
function to manage rejection.
Here's an example that makes use of the code above:
getEmployeeNames()
.then(function(results){
render(results)
})
.catch(function(err){
console.log("Promise rejection error: "+err);
})
At this point you can set up the view for your results (which are indeed returned as an array of objects):
render = function(results){ for (var i in results) console.log(results[i].Name) }
Edit
I'm adding a basic example on how to return HTML content with the results, which is a more typical scenario for Node. Just use the then
function of the promise to set the HTTP response, and open your browser at http://localhost:3001
require('http').createServer( function(req, res){
if(req.method == 'GET'){
if(req.url == '/'){
res.setHeader('Content-type', 'text/html');
getEmployeeNames()
.then(function(results){
html = "<h2>"+results.length+" employees found</h2>"
html += "<ul>"
for (var i in results) html += "<li>" + results[i].Name + " " +results[i].Surname + "</li>";
html += "</ul>"
res.end(html);
})
.catch(function(err){
console.log("Promise rejection error: "+err);
res.end("<h1>ERROR</h1>")
})
}
}
}).listen(3001)
Cool. I've done this with another script, but when I try to move from console.log of results to putting them in an array, I get nothing. What's the solution when I don't want it going to console?
– Ken Ingram
Jun 27 '18 at 22:22
@KenIngram you should post your code: what are you trying to do? Therender
function I posted gets the array as parameter, soresults
is your array of objects. If you print it directly you'll get something like[ RowDataPacket { Name: 'James' }, RowDataPacket { Name: 'Mary' } ]
. You can also access array properties likeresults.length
.
– gtugnolo
Jun 29 '18 at 9:20
I was able to get some help on the Promises. Now that I understand it, your example makes complete sense.
– Ken Ingram
Jul 29 '18 at 20:11
add a comment |
I guess what you really want to do here is returning a Promise object with the results. This way you can deal with the async operation of retrieving data from the DBMS: when you have the results, you make use of the Promise resolve function to somehow "return the value" / "resolve the promise".
Here's an example:
getEmployeeNames = function(){
return new Promise(function(resolve, reject){
connection.query(
"SELECT Name, Surname FROM Employee",
function(err, rows){
if(rows === undefined){
reject(new Error("Error rows is undefined"));
}else{
resolve(rows);
}
}
)}
)}
On the caller side, you use the then
function to manage fulfillment, and the catch
function to manage rejection.
Here's an example that makes use of the code above:
getEmployeeNames()
.then(function(results){
render(results)
})
.catch(function(err){
console.log("Promise rejection error: "+err);
})
At this point you can set up the view for your results (which are indeed returned as an array of objects):
render = function(results){ for (var i in results) console.log(results[i].Name) }
Edit
I'm adding a basic example on how to return HTML content with the results, which is a more typical scenario for Node. Just use the then
function of the promise to set the HTTP response, and open your browser at http://localhost:3001
require('http').createServer( function(req, res){
if(req.method == 'GET'){
if(req.url == '/'){
res.setHeader('Content-type', 'text/html');
getEmployeeNames()
.then(function(results){
html = "<h2>"+results.length+" employees found</h2>"
html += "<ul>"
for (var i in results) html += "<li>" + results[i].Name + " " +results[i].Surname + "</li>";
html += "</ul>"
res.end(html);
})
.catch(function(err){
console.log("Promise rejection error: "+err);
res.end("<h1>ERROR</h1>")
})
}
}
}).listen(3001)
I guess what you really want to do here is returning a Promise object with the results. This way you can deal with the async operation of retrieving data from the DBMS: when you have the results, you make use of the Promise resolve function to somehow "return the value" / "resolve the promise".
Here's an example:
getEmployeeNames = function(){
return new Promise(function(resolve, reject){
connection.query(
"SELECT Name, Surname FROM Employee",
function(err, rows){
if(rows === undefined){
reject(new Error("Error rows is undefined"));
}else{
resolve(rows);
}
}
)}
)}
On the caller side, you use the then
function to manage fulfillment, and the catch
function to manage rejection.
Here's an example that makes use of the code above:
getEmployeeNames()
.then(function(results){
render(results)
})
.catch(function(err){
console.log("Promise rejection error: "+err);
})
At this point you can set up the view for your results (which are indeed returned as an array of objects):
render = function(results){ for (var i in results) console.log(results[i].Name) }
Edit
I'm adding a basic example on how to return HTML content with the results, which is a more typical scenario for Node. Just use the then
function of the promise to set the HTTP response, and open your browser at http://localhost:3001
require('http').createServer( function(req, res){
if(req.method == 'GET'){
if(req.url == '/'){
res.setHeader('Content-type', 'text/html');
getEmployeeNames()
.then(function(results){
html = "<h2>"+results.length+" employees found</h2>"
html += "<ul>"
for (var i in results) html += "<li>" + results[i].Name + " " +results[i].Surname + "</li>";
html += "</ul>"
res.end(html);
})
.catch(function(err){
console.log("Promise rejection error: "+err);
res.end("<h1>ERROR</h1>")
})
}
}
}).listen(3001)
edited Jun 29 '18 at 10:30
answered Jun 27 '18 at 13:49
gtugnologtugnolo
712
712
Cool. I've done this with another script, but when I try to move from console.log of results to putting them in an array, I get nothing. What's the solution when I don't want it going to console?
– Ken Ingram
Jun 27 '18 at 22:22
@KenIngram you should post your code: what are you trying to do? Therender
function I posted gets the array as parameter, soresults
is your array of objects. If you print it directly you'll get something like[ RowDataPacket { Name: 'James' }, RowDataPacket { Name: 'Mary' } ]
. You can also access array properties likeresults.length
.
– gtugnolo
Jun 29 '18 at 9:20
I was able to get some help on the Promises. Now that I understand it, your example makes complete sense.
– Ken Ingram
Jul 29 '18 at 20:11
add a comment |
Cool. I've done this with another script, but when I try to move from console.log of results to putting them in an array, I get nothing. What's the solution when I don't want it going to console?
– Ken Ingram
Jun 27 '18 at 22:22
@KenIngram you should post your code: what are you trying to do? Therender
function I posted gets the array as parameter, soresults
is your array of objects. If you print it directly you'll get something like[ RowDataPacket { Name: 'James' }, RowDataPacket { Name: 'Mary' } ]
. You can also access array properties likeresults.length
.
– gtugnolo
Jun 29 '18 at 9:20
I was able to get some help on the Promises. Now that I understand it, your example makes complete sense.
– Ken Ingram
Jul 29 '18 at 20:11
Cool. I've done this with another script, but when I try to move from console.log of results to putting them in an array, I get nothing. What's the solution when I don't want it going to console?
– Ken Ingram
Jun 27 '18 at 22:22
Cool. I've done this with another script, but when I try to move from console.log of results to putting them in an array, I get nothing. What's the solution when I don't want it going to console?
– Ken Ingram
Jun 27 '18 at 22:22
@KenIngram you should post your code: what are you trying to do? The
render
function I posted gets the array as parameter, so results
is your array of objects. If you print it directly you'll get something like [ RowDataPacket { Name: 'James' }, RowDataPacket { Name: 'Mary' } ]
. You can also access array properties like results.length
.– gtugnolo
Jun 29 '18 at 9:20
@KenIngram you should post your code: what are you trying to do? The
render
function I posted gets the array as parameter, so results
is your array of objects. If you print it directly you'll get something like [ RowDataPacket { Name: 'James' }, RowDataPacket { Name: 'Mary' } ]
. You can also access array properties like results.length
.– gtugnolo
Jun 29 '18 at 9:20
I was able to get some help on the Promises. Now that I understand it, your example makes complete sense.
– Ken Ingram
Jul 29 '18 at 20:11
I was able to get some help on the Promises. Now that I understand it, your example makes complete sense.
– Ken Ingram
Jul 29 '18 at 20:11
add a comment |
This was a situation where I was inserting new records to a child table and needed the prent record key, based only on a name.
This was a good example of understanding the asynchronous nature of node.
I needed to wrap the all the code affecting the child records inside the call to find the parent record id.
I was approaching this from a sequential (PHP, JAVA) perspective, which was all wrong.
add a comment |
This was a situation where I was inserting new records to a child table and needed the prent record key, based only on a name.
This was a good example of understanding the asynchronous nature of node.
I needed to wrap the all the code affecting the child records inside the call to find the parent record id.
I was approaching this from a sequential (PHP, JAVA) perspective, which was all wrong.
add a comment |
This was a situation where I was inserting new records to a child table and needed the prent record key, based only on a name.
This was a good example of understanding the asynchronous nature of node.
I needed to wrap the all the code affecting the child records inside the call to find the parent record id.
I was approaching this from a sequential (PHP, JAVA) perspective, which was all wrong.
This was a situation where I was inserting new records to a child table and needed the prent record key, based only on a name.
This was a good example of understanding the asynchronous nature of node.
I needed to wrap the all the code affecting the child records inside the call to find the parent record id.
I was approaching this from a sequential (PHP, JAVA) perspective, which was all wrong.
answered Aug 7 '15 at 11:40
Ken IngramKen Ingram
56351431
56351431
add a comment |
add a comment |
Easier if you send in a promise to be resolved
e.g
function get_info(data, promise){
var sql = "SELECT a from b where info = data";
connection.query(sql, function(err, results){
if (err){
throw err;
}
console.log(results[0].objid); // good
stuff_i_want = results[0].objid; // Scope is larger than function
promise.resolve(results[0].objid);
}
}
This way Node.js will stay fast because it's busy doing other things while your promise is waiting to be resolved
Thanks. I've been trying to implement Promises. I am stuck at converting the returned promise into usable data. I understand the concept, however, how to complete the technical implementation is eluding me.
– Ken Ingram
Sep 13 '17 at 22:08
1
db.findOne(272).then((user) => { console.log("Find user in location strategy", user[0]); return done(null, user[0]); }).catch(error => { return done(err); });
– Epirocks
Sep 13 '17 at 23:34
I keep looking at this. It's an answer, but it assumes I understand how to make sense of it. I figured out Promises, but his snippet never actually helped. I needed a simpler breakdown. Neurodiverse.
– Ken Ingram
Dec 28 '18 at 4:22
add a comment |
Easier if you send in a promise to be resolved
e.g
function get_info(data, promise){
var sql = "SELECT a from b where info = data";
connection.query(sql, function(err, results){
if (err){
throw err;
}
console.log(results[0].objid); // good
stuff_i_want = results[0].objid; // Scope is larger than function
promise.resolve(results[0].objid);
}
}
This way Node.js will stay fast because it's busy doing other things while your promise is waiting to be resolved
Thanks. I've been trying to implement Promises. I am stuck at converting the returned promise into usable data. I understand the concept, however, how to complete the technical implementation is eluding me.
– Ken Ingram
Sep 13 '17 at 22:08
1
db.findOne(272).then((user) => { console.log("Find user in location strategy", user[0]); return done(null, user[0]); }).catch(error => { return done(err); });
– Epirocks
Sep 13 '17 at 23:34
I keep looking at this. It's an answer, but it assumes I understand how to make sense of it. I figured out Promises, but his snippet never actually helped. I needed a simpler breakdown. Neurodiverse.
– Ken Ingram
Dec 28 '18 at 4:22
add a comment |
Easier if you send in a promise to be resolved
e.g
function get_info(data, promise){
var sql = "SELECT a from b where info = data";
connection.query(sql, function(err, results){
if (err){
throw err;
}
console.log(results[0].objid); // good
stuff_i_want = results[0].objid; // Scope is larger than function
promise.resolve(results[0].objid);
}
}
This way Node.js will stay fast because it's busy doing other things while your promise is waiting to be resolved
Easier if you send in a promise to be resolved
e.g
function get_info(data, promise){
var sql = "SELECT a from b where info = data";
connection.query(sql, function(err, results){
if (err){
throw err;
}
console.log(results[0].objid); // good
stuff_i_want = results[0].objid; // Scope is larger than function
promise.resolve(results[0].objid);
}
}
This way Node.js will stay fast because it's busy doing other things while your promise is waiting to be resolved
answered Sep 13 '17 at 17:46
EpirocksEpirocks
331110
331110
Thanks. I've been trying to implement Promises. I am stuck at converting the returned promise into usable data. I understand the concept, however, how to complete the technical implementation is eluding me.
– Ken Ingram
Sep 13 '17 at 22:08
1
db.findOne(272).then((user) => { console.log("Find user in location strategy", user[0]); return done(null, user[0]); }).catch(error => { return done(err); });
– Epirocks
Sep 13 '17 at 23:34
I keep looking at this. It's an answer, but it assumes I understand how to make sense of it. I figured out Promises, but his snippet never actually helped. I needed a simpler breakdown. Neurodiverse.
– Ken Ingram
Dec 28 '18 at 4:22
add a comment |
Thanks. I've been trying to implement Promises. I am stuck at converting the returned promise into usable data. I understand the concept, however, how to complete the technical implementation is eluding me.
– Ken Ingram
Sep 13 '17 at 22:08
1
db.findOne(272).then((user) => { console.log("Find user in location strategy", user[0]); return done(null, user[0]); }).catch(error => { return done(err); });
– Epirocks
Sep 13 '17 at 23:34
I keep looking at this. It's an answer, but it assumes I understand how to make sense of it. I figured out Promises, but his snippet never actually helped. I needed a simpler breakdown. Neurodiverse.
– Ken Ingram
Dec 28 '18 at 4:22
Thanks. I've been trying to implement Promises. I am stuck at converting the returned promise into usable data. I understand the concept, however, how to complete the technical implementation is eluding me.
– Ken Ingram
Sep 13 '17 at 22:08
Thanks. I've been trying to implement Promises. I am stuck at converting the returned promise into usable data. I understand the concept, however, how to complete the technical implementation is eluding me.
– Ken Ingram
Sep 13 '17 at 22:08
1
1
db.findOne(272).then((user) => { console.log("Find user in location strategy", user[0]); return done(null, user[0]); }).catch(error => { return done(err); });
– Epirocks
Sep 13 '17 at 23:34
db.findOne(272).then((user) => { console.log("Find user in location strategy", user[0]); return done(null, user[0]); }).catch(error => { return done(err); });
– Epirocks
Sep 13 '17 at 23:34
I keep looking at this. It's an answer, but it assumes I understand how to make sense of it. I figured out Promises, but his snippet never actually helped. I needed a simpler breakdown. Neurodiverse.
– Ken Ingram
Dec 28 '18 at 4:22
I keep looking at this. It's an answer, but it assumes I understand how to make sense of it. I figured out Promises, but his snippet never actually helped. I needed a simpler breakdown. Neurodiverse.
– Ken Ingram
Dec 28 '18 at 4:22
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f31875621%2fhow-to-properly-return-a-result-from-mysql-with-node%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown