Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

javascript - Nodejs MySQL connection query return value to function call

I am trying get value from database. Trying it out with a demo example. But I am having problem to synchronize the calls, tried using callback function. I am beginner in node.js, so don't know if this is the right way.

FILE 1 : app.js

var data;

var db = require('./db.js');

var query = 'SELECT 1 + 1 AS solution';

var r = db.demo(query, function(result) { data = result; });

console.log( 'Data : ' + data);

FILE 2 : db.js

var mysql      = require('./node_modules/mysql');

var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'root',
});

module.exports.demo = function(queryString, callback) {
    try {
        connection.connect();
        console.log('Step 1');

        connection.query(queryString, function(err, rows, fields) {
            console.log('Step 2');
            if (err) {
                console.log("ERROR : " + err);
            }
            console.log('The solution is: ', rows[0].solution);

            callback(rows[0].solution);

            return rows[0].solution;
        });
        callback();

        connection.end();
        console.log('Step 3');
    }
    catch(ex) {
        console.log("EXCEPTION : " + ex);
    }
};

OUTPUT :

Step 1
Step 3
Data : undefined
Step 2
The solution is:  2

Referred to this question also, but it didnt solve my problem : nodeJS return value from callback

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The issue is this:

var r = db.demo(query, function(result) { data = result; });

console.log( 'Data : ' + data);

The console.log will run before the callback function gets called, because db.demo is asynchronous, meaning that it might take some time to finish, but all the while the next line of the code, console.log, will be executed.

If you want to access the results, you need to wait for the callback function to be called:

var r = db.demo(query, function(result) { 
  console.log( 'Data : ' + result);
});

This is how most code dealing with I/O will function in Node, so it's important to learn about it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...