在节点和回调中分隔 functions/files

separating functions/files in node and callbacks

我试图将我的代码组织在 3 个文件中

以便对于 GET 请求,我可以使用结果行进行响应。我根本无法理解回调函数。我怎样才能 return 将结果行发送给客户端?

文件:db_queries.js

function getUserData (userId, fn){
    client.query("select * from participationTable where ? in (userId1, userId2)", userId, function(err,rows){
        if (err) {
            return fn(new Error('(customError) unable to find ongoing games'));
        } else {
            return fn(null, rows);
        }
    });
}
module.exports.getUserData = getUserData;

文件:general_functions.js

var db = require('./db_queries');
function getUserParticipationDeatils(req, function(err, rows){
    db.getUserData(req.user.userId, function(err, rows){
            if (err){ return done(err); }
            // 'rows' is accessible here
            // but how can I send it ?
        });
});
module.exports.getUserParticipationDeatils = getUserParticipationDeatils;

文件:basic_routes.js

var general_functions = require('./general_functions');
app.get('/getUserParticipation', function (req, res) {  
    general_functions.getUserParticipationDeatils(req, function(err, rows){
        if (err){ return done(err); }
        return res.send(JSON.stringify(rows));
    }); 
});

请帮我构造文件中的函数general_functions.js

更改您的 getUserParticipationDeatils 以接受回调 fn,就像您的 getUserData 函数一样。

像这样:

var db = require('./db_queries');
function getUserParticipationDeatils(req, fn){
    db.getUserData(req.user.userId, function(err, rows){
        if (err){ return fn(err); }
        fn(null, rows);
    });
});
module.exports.getUserParticipationDeatils = getUserParticipationDeatils;