如何在module.export函数中使用回调来进行mysql查询 - nodejs,express

时间:2021-07-14 15:44:55

I have the following code structure in exports.js

我在exports.js中有以下代码结构

module.exports = {
    getData:function(param1,param2,callback){
        sql.query('SELECT users FROM table',function(error,result){
            callback(null,result[0]);
        });
    }
}

And I called it from main file app.js file like

我从主文件app.js文件中调用它

var common = require('./exports');
console.log(common.getData(null,null));

I got the following error

我收到以下错误

TypeError: callback is not a function

However I found a similar question here. But didn't fixed the problem. Any help would be appreciated..!

但是我在这里发现了类似的问题。但没有解决问题。任何帮助,将不胜感激..!

2 个解决方案

#1


0  

getData() accepts 3 arguments

getData()接受3个参数

The last of which should be a function which you have not provided in your example. Add a callback function in your call like so:

最后一个应该是您在示例中未提供的功能。在你的通话中添加一个回调函数,如下所示:

common.getData(null,null, function(err, result) {

    console.log(result)

});

The sql.query function uses the callback function you pass in as the third parameter and thats why your getting the error to say it's missing.

sql.query函数使用你传入的回调函数作为第三个参数,这就是为什么你得错误说它丢失了。

#2


1  

if you want print results

如果你想要打印结果

var common = require('./exports');
common.getData(null, null, function(err, result){
    console.log(result)l
})

#1


0  

getData() accepts 3 arguments

getData()接受3个参数

The last of which should be a function which you have not provided in your example. Add a callback function in your call like so:

最后一个应该是您在示例中未提供的功能。在你的通话中添加一个回调函数,如下所示:

common.getData(null,null, function(err, result) {

    console.log(result)

});

The sql.query function uses the callback function you pass in as the third parameter and thats why your getting the error to say it's missing.

sql.query函数使用你传入的回调函数作为第三个参数,这就是为什么你得错误说它丢失了。

#2


1  

if you want print results

如果你想要打印结果

var common = require('./exports');
common.getData(null, null, function(err, result){
    console.log(result)l
})