Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


Javascript help needed (returning the value from MySQL in a function) - Page 2
New on LowEndTalk? Please Register and read our Community Rules.

All new Registrations are manually reviewed and approved, so a short delay after registration may occur before your account becomes active.

Javascript help needed (returning the value from MySQL in a function)

24

Comments

  • KuJoeKuJoe Member, Host Rep

    I don't really want to learn a new concept though. I'm not a software developer, I code for fun. If it's not fun it's not worth it for me.

  • @KuJoe - I hope I'm not too late to provide some inputs.

    Here's what is happening:

    Sequentially - you are calling function GetQuote and (from the gist) all is well till line 11 (and line 10 correctly logs the "3" message). Line 11 is analogous to a background job. It is an async function and at this point a separate thread is forked off to execute the query. Because of the way it is setup, what happens when the query "completes" (returns), the separate thread will execute lines 12..17 of the gist (which is the body of the unnamed, inline function starting with the { on line 11 and ending on line 18.

    Now the "main" thread continues along after the function (line 19) which then returns to the caller of GetQuote and continues to the console.log(msg) line [which is what you are using to call the funciton]. At this point, msg is undefined (out of scope in the main thread and so the undefined is logged).

    Meanwhile in parallel the query is running in the separate thread and when it completes, execution continues to line 12 (gist) and you get the "4" logged after which the "correct" value is logged (gist line 15).

    Now onto your bug problem of "returning" msg. Because this msg is in a separate thread, there's no way to simply return to the main thread (which is doing something else somewhere else..). So what you can do is to call some other (predefined/global) function to do something with msg - maybe print it or stuff it somewhere else or do whatever with it (but note that this will be all running in the "scope" of this separate thread which was spawned to run the query).

    Hope this helps and I really hope you're able to wrap this "nicely" so that you don't have to throw away whatever work you've built so far.

    All that is fundamentally different is the threaded (aka async) manner of doing things which requires a little getting used to after which I'm sure you'll hum along nicely.

    Thanked by 1raindog308
  • @KuJoe said:
    I don't really want to learn a new concept though. I'm not a software developer, I code for fun. If it's not fun it's not worth it for me.

    That's the thing with node.js. How the code works is is somewhat confusing. Because most of the times, the code is not executed in chronological order (unlike php, vb, .net and others).

    When we query the database, in other language (e.g. php), it will wait until we get the result from the database.

    But in node.js, When we query the database, it won't wait for the result, the next line of code is executed immediately. That's why the when you try to log the variable it says undefined. Because at the time the of the log the variable result still, well, undefined.

    Good Luck, on whatever you are doing anyway.

  • @KuJoe I dont usually node.js but in js normally you would do a callback to wait the results. Check this out: https://stackoverflow.com/questions/31775177/nodejs-and-mysql-wait-for-query-result

  • raindog308raindog308 Administrator, Veteran

    LTniger said: Try Cobol, Go. Then you will know what is complicated.

    I've coded in both those languages and I didn't find either had the mental-hoops-jumping that's needed for Node.JS.

    COBOL is just a simple procedural language. If you know nearly any other language, COBOL is easy to grasp. Recently (relative to its lifetime) they've added OOP, etc. but even that is pretty simple. I don't know why anyone who codes would find COBOL hard.

    Go requires a little more thought but (a) you can write a ton of code without getting heavy into its parallelism, and (b) the parallelism is baked in and well thought out, so it's not hard to

    perhaps the simplest. There are some new concepts, but they're mostly optional until you need them and the core language is pleasantly familiar.

    OTOH, NodeJS is a radically different paradigm. It's not the code - If you know JavaScript, which is easy to learn if you don't - but rather the way it's written and the foundational assumptions.

    I think a php guy could pick up python or Go or COBOL much more easily than NodeJS.

    Thanked by 1Hxxx
  • BharatBBharatB Member, Patron Provider

    @Kujoe

    So since nodejs is a async based functionality you cant return stuff from a function however you can use a callback function instead to process next.

    Thanked by 1Hxxx
  • KuJoeKuJoe Member, Host Rep

    Attempts to use "callback" result in the follow error every time:

    TypeError: callback is not a function

    New code: https://gist.github.com/KuJoe/7615a1448d7ec4cb44ae5e504a9f1652

  • BochiBochi Member
    edited September 2017

    @KuJoe said:
    Attempts to use "callback" result in the follow error every time:

    TypeError: callback is not a function

    The mentioned callback() was just a generic description of what you should implement. ;)
    You did not define a function named that way, so you are getting this error.

    You are using the anonymous function correctly - this function is getting passed the result after it is retrieved. The logging of the desired value within should work!
    However, you will find yourself in another context there, so returning the value from within there is not what you wanna do.

  • @KuJoe Here it goes, a formal how to Node, Mysql and callbacks:
    https://www.sitepoint.com/using-node-mysql-javascript-client/

    BTW i just noticed this is exactly what some of the other people replied to you. Take a look.

  • KuJoeKuJoe Member, Host Rep

    Soooooo... time to go learn Python. :D

  • @KuJoe said:
    Soooooo... time to go learn Python. :D

    Haha :D Come on, don't give up this quick!

  • CConnerCConner Member, Host Rep

    @KuJoe If you are clueless about callbacks I suggest you learn JavaScript first before you have a go at Node.JS

  • KuJoeKuJoe Member, Host Rep

    @CConner said:
    @KuJoe If you are clueless about callbacks I suggest you learn JavaScript first before you have a go at Node.JS

    I thought Node.JS and JavaScript were the same language? This was my attempt to learn JS but it's obvious it's not a language I will probably ever need or take advantage of.

  • @KuJoe

    Node.js is an open-source, cross-platform JavaScript run-time environment for executing JavaScript code server-side. Historically, JavaScript was used primarily for client-side scripting, in which scripts written in JavaScript are embedded in a webpage's HTML, to be run client-side by a JavaScript engine in the user's web browser. Node.js enables JavaScript to be used for server-side scripting, and runs scripts server-side to produce dynamic web page content before the page is sent to the user's web browser. Consequently, Node.js has become one of the foundational elements of the "JavaScript everywhere" paradigm,[5] allowing web application development to unify around a single programming language, rather than rely on a different language for writing server side scripts.

  • jackbjackb Member, Host Rep

    @KuJoe said:

    @CConner said:
    @KuJoe If you are clueless about callbacks I suggest you learn JavaScript first before you have a go at Node.JS

    I thought Node.JS and JavaScript were the same language? This was my attempt to learn JS but it's obvious it's not a language I will probably ever need or take advantage of.

    I'd suggest learning front end first. Don't worry about node until you have a grasp of JavaScript in general.

  • KuJoeKuJoe Member, Host Rep

    @Hxxx said:

    Yeah, that's what I thought. What was I incorrect about so I can reword it better?

  • This works I had to setup mysql as I usually use postgres. This was just a bunch of names I generated.

    var mysql = require("mysql");
    
    function getQuote() {
      return new Promise(function(resolve, reject) {
        var con = mysql.createConnection({
          host: "127.0.0.1",
          user: "root",
          password: "password",
          database: "test"
        });
    
        var query_string = "SELECT name " + "FROM testtable";
    
        con.query(query_string, function(err, rows, fields) {
          if (err) {
            return reject(err);
          }
          resolve(rows);
        });
      });
    }
    
    getQuote()
      .then(rows => console.log(rows))
      .catch(err => console.log(err));
    
  • CConnerCConner Member, Host Rep

    KuJoe said: I thought Node.JS and JavaScript were the same language? This was my attempt to learn JS but it's obvious it's not a language I will probably ever need or take advantage of.

    They are both virtually the same language with Node.JS having some minor differences. Node.JS and JavaScript are both async in its function execution as well.

    Node.JS is a programming language that is often used for applications that need to do a lot at once, this is where languages such as PHP fall short. Node is also really well documented, and there are loads of free modules out there that do all kinds of stuff.

  • Python is a better route tho @KuJoe

    Very useful in the field of Data Science

    Thanked by 1KuJoe
  • CConnerCConner Member, Host Rep

    Hxxx said: Python is a better route tho @KuJoe

    Depends.

  • He started learning node.js with something else in mind. Python is strong/solid choice almost for anything.

    @CConner said:

    Hxxx said: Python is a better route tho @KuJoe

    Depends.

  • @Hxxx said:
    He started learning node.js with something else in mind. Python is strong/solid choice almost for anything.

    @CConner said:

    Hxxx said: Python is a better route tho @KuJoe

    Depends.

    If you have OCD it is a great language to start out in.

    Thanked by 1Hxxx
  • No OCD here. According to the media buying a fidget spinner might help you.

    @Farish said:

    @Hxxx said:
    He started learning node.js with something else in mind. Python is strong/solid choice almost for anything.

    @CConner said:

    Hxxx said: Python is a better route tho @KuJoe

    Depends.

    If you have OCD it is a great language to start out in.

  • CConnerCConner Member, Host Rep
    edited September 2017

    Python is an all-round language, that does not mean it is good at everything. Better to use the right size screwdriver that fits the hole than one that claims to fit nearly all.

  • @CConner said:
    Python is an all-round language, that does not mean it is good at everything. Better to use the right size screwdriver that fits the hole than one that claims to fit nearly all.

    Somewhere out in the internet you have now been put on a python watch list, whenever you type text, it will magically indent itself in wrong spacing to cause you great angst.

    Thanked by 1WSS
  • KuJoeKuJoe Member, Host Rep

    @CConner said:

    KuJoe said: I thought Node.JS and JavaScript were the same language? This was my attempt to learn JS but it's obvious it's not a language I will probably ever need or take advantage of.

    They are both virtually the same language with Node.JS having some minor differences. Node.JS and JavaScript are both async in its function execution as well.

    That's what I thought. I'm confused as to why you said "learn JS before you try to use JS". Either way, I think I've learned all I need to know about JS and that is that it's not the right language for me or my needs. :)

  • @KuJoe said:
    Soooooo... time to go learn Python. :D

    import ihatepythonformatting

  • @KuJoe said:

    @CConner said:

    KuJoe said: I thought Node.JS and JavaScript were the same language? This was my attempt to learn JS but it's obvious it's not a language I will probably ever need or take advantage of.

    They are both virtually the same language with Node.JS having some minor differences. Node.JS and JavaScript are both async in its function execution as well.

    That's what I thought. I'm confused as to why you said "learn JS before you try to use JS". Either way, I think I've learned all I need to know about JS and that is that it's not the right language for me or my needs. :)

    Did you try the updated code? I am getting data from MySQL being returned.

  • If you are doing something that have to deal with front-end, hopefully you use JS and make the UX/UI work fluently instead of doing a refresh every time the customer does a click. I mean... well shit it is 2017. There is nothing more agonizing than using something that refreshes the whole page every time an action is being executed.

  • I'm thinking @joepie91

    Just realised his user name is joe pie. Not Josepie. I've been living in a lie.

Sign In or Register to comment.