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;
}







6















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










share|improve this question































    6















    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










    share|improve this question



























      6












      6








      6


      4






      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










      share|improve this question
















      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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Aug 7 '15 at 11:12







      Ken Ingram

















      asked Aug 7 '15 at 10:32









      Ken IngramKen Ingram

      56351431




      56351431
























          4 Answers
          4






          active

          oldest

          votes


















          9














          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#






          share|improve this answer



















          • 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 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











          • 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





















          4














          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)





          share|improve this answer


























          • 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













          • 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



















          1














          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.






          share|improve this answer































            1














            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






            share|improve this answer
























            • 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












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


            }
            });














            draft saved

            draft discarded


















            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









            9














            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#






            share|improve this answer



















            • 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 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











            • 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


















            9














            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#






            share|improve this answer



















            • 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 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











            • 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
















            9












            9








            9







            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#






            share|improve this answer













            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#







            share|improve this answer












            share|improve this answer



            share|improve this answer










            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 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











            • 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





              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











            • 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















            4














            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)





            share|improve this answer


























            • 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













            • 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
















            4














            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)





            share|improve this answer


























            • 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













            • 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














            4












            4








            4







            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)





            share|improve this answer















            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)






            share|improve this answer














            share|improve this answer



            share|improve this answer








            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? 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



















            • 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













            • 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











            1














            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.






            share|improve this answer




























              1














              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.






              share|improve this answer


























                1












                1








                1







                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.






                share|improve this answer













                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.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Aug 7 '15 at 11:40









                Ken IngramKen Ingram

                56351431




                56351431























                    1














                    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






                    share|improve this answer
























                    • 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
















                    1














                    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






                    share|improve this answer
























                    • 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














                    1












                    1








                    1







                    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






                    share|improve this answer













                    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







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    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



















                    • 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


















                    draft saved

                    draft discarded




















































                    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.




                    draft saved


                    draft discarded














                    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





















































                    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







                    Popular posts from this blog

                    MongoDB - Not Authorized To Execute Command

                    in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                    Npm cannot find a required file even through it is in the searched directory