ReferenceError:传递回调参数

时间:2018-01-23 15:05:02

标签: javascript mysql node.js

当我尝试调用回调方法时,我的参数未定义,只有在先前定义了回调函数时。将参数传递给先前声明的方法的正确方法是什么?

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

function doQuery(query, callback){
  connection.connect();
  connection.query(query, callback(error, results,fields)); 
  connection.end();
}

doQuery('SELECT 1 + 1 AS sum', function (){
  if (error) throw error;
  console.log(results[0].sum);
})
ReferenceError: error is not defined
    at doQuery (/home/usr/workspace/project/code.js:11:36)
    at Object.<anonymous> (/home/usr/workspace/project/code.js:15:1)
    at Module._compile (module.js:643:30)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Function.Module.runMain (module.js:684:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

2 个答案:

答案 0 :(得分:1)

  

需要添加错误参数函数(错误){以便它可以在函数内部使用

doQuery('SELECT 1 + 1 AS sum', function (error){
      if (error) throw error;
      console.log(results[0].sum);
    })

答案 1 :(得分:1)

你必须像这样返回你的回调:

function doQuery(query, callback){
    connection.query(query, (error, results, fields)=> {
         callback(error, results, fields);
    })
}