Nodejs MySQL连接查询返回值以调用函数 [英] Nodejs MySQL connection query return value to function call

查看:168
本文介绍了Nodejs MySQL连接查询返回值以调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从数据库中获取价值.用一个演示示例进行尝试.但是我在使用回调函数尝试同步调用时遇到问题.我是node.js的初学者,所以不知道这是正确的方法.

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.

文件1:app.js

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

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

输出:

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

也提到了这个问题,但是并没有解决我的问题: nodeJS从回调返回值

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

推荐答案

问题是这样的:

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

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

console.log将在调用回调函数之前运行,因为db.demo是异步的,这意味着可能要花一些时间才能完成,但是始终将代码的下一行console.log被执行.

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

这是大多数处理I/O的代码将在Node中起作用的方式,因此了解它非常重要.

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

这篇关于Nodejs MySQL连接查询返回值以调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆