简体   繁体   中英

How to use “results” variable (callback function) inside query mysql in another function (Nodejs mysql)

I have a project, to store every message that pass through mosquitto (mqtt) installed in CentOS7 to mysql database. I use Nodejs to store message that pass through.

And then I display that message in my website. I put "add device" function to add new table in database based on total data every device. (If i had device named "device1" that store temperature and humidity, it will create new table named "device1" and 3 column, id, humidity, and temperature.)

I have a problem. I want to use "results" variable from callback function inside query mysql in javascript. I want to use that variable outside that function.

Here is the code:

var sql= "SELECT count(*) AS hitung FROM information_schema.columns WHERE table_name = 'device' ";

connection.query(sql, function (error, results) {
    if (error) throw error;
    console.log(results[0].hitung);
});

Based on the example I gave above (device1). Console.log will print '3' (because of 3 columns).

I want to use it (the results[0].hitung value) in another function like:

function example() {
    for (i=1; i<=results[0].hitung; i++) {
        console.log(i);
    };
};

But it show error, that I can use that variable. Im new in website development, because i have interest in only networking. Sorry for my bad english, hope you understand my problem. Im new in this community. Thank you.

I want to use it (the results[0].hitung value) in another function like

To do that, you'll need to call example from within your query callback function, exactly like you did with console.log , eg:

connection.query(sql, function (error, results) {
    if (error) throw error;
    example(results); // <===
});

That's because:

  1. results is scoped to that callback, and
  2. You have to wait for the callback before you have the results

You might look into using promises , and into using async functions (which create and consume promises). You can use util.promisify to convert Node callback-style functions to promises, although most APIs are actively adopting promises, and there are promise wrapper libs for a lot of other APIS (for instance, mysql-promise for mysql and mysql2 ). That might help by allowing you to write asynchronous code using standard flow-control mechanisms that used to only work for synchronous code.

You can add a parameter to your function like this:

function example(results) {
    for (i=1; i<=results.length; i++) {
        console.log(results[0].hitung)
    };
};

Then you call the function from your query callback:

connection.query(sql, function (error, results) {
    if (error) throw error;
    example(results);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM