使用回调mysql函数

时间:2014-10-15 14:32:02

标签: javascript mysql node.js

我在合并回调函数/ mysql查询时遇到问题:

var mysql      = require('mysql');
var connection = mysql.createConnection({
    host : '100.100.100.100',
    user : 'userX',
    password: 'passwordX'
});

connection.connect();
connection.query('use db1');
connection.query("SELECT nick FROM users WHERE id=1", function(err, rows, fields) {

    if(rows.length!=0){
        //here "UPDATE users SET mac = "+macAddress+" WHERE id = 1;"
    }

    //here "SELECT COUNT(*) as Counter FROM users WHERE id = 1;"
    //if(Counter>1){console.log('doubled mac');
});

我有一个来自函数的变量macAdress:

require('getmac').getMac(function(err, macAddress){
    if (err){ throw err; }
    console.log(macAddress);    
});

模块:

https://github.com/felixge/node-mysql/

https://github.com/bevry/getmac

1 个答案:

答案 0 :(得分:0)

查看async模块,它为异步编程提供了很好的帮助。

其主要功能之一是waterfall,它将异步操作与可读代码相结合,您需要的内容如下所示:

var mysql      = require('mysql');
var async      = require('async');
var connection = mysql.createConnection({
        host : '100.100.100.100',
        user : 'userX',
        password: 'passwordX'
    });
connection.connect();
connection.query('use db1');
var macAddress;
async.waterfall([
    function(next){
        require('getmac').getMac(next);
    },
    function(ma, next){
      macAddress=ma; // store it globaly for further usage
      connection.query("SELECT nick FROM users WHERE id=1", next);
    },
    function(rows, fields, next){
        if(rows.length!=0){
          connection.query("UPDATE users SET mac = "+macAddress+" WHERE id = 1", next);
        } else {
          next(new Error("No Users found")); // do this if you want to stop here, else just call next(null); to proceed with the next function
        }
    },
    function(res, next) { // im not sure what args u get in return from the update sql query, you need to replace res with them
      connection.query("SELECT COUNT(*) as Counter FROM users WHERE id = 1", next);
    }
], function (err, result) { // should probably be err, rows, fields 
   if (err) console.log("Got Error:", err);
   console.log("Got Result:", result); 
});