Node.js:异步回调混乱

Node.js: Asynchronous callback confusion

我正在尝试弄清楚如何为 Web 应用程序创建异步函数。我正在进行数据库查询,将数据处理为更方便的格式,然后尝试设置我的路由器以传回该文件。

//Module 1
//Module 1 has 2 functions, both are necessary to properly format
function fnA(param1){
    db.cypherQuery(query, function(err, result){
        if(err){
            return err;
        }
        var reformattedData = {};
        //code that begins storing re-formatted data in reformattedData

        //the function that handles the rest of the formatting
        fnB(param1, param2);
    });
});

function fnB(param1, reformattedData){
    db.cypherQuery(query, function(err, result){
        if(err){
            return err;
        }
        //the rest of the reformatting that uses bits from the second query 
        return reformattedData;
    });
});

exports.fnA = fnA;

然后在我的路由器文件中:

var db = require('module1');

router.get('/url', function(req,res,next){
    db.fnA(param1, function(err, result){
        if (err){
            return next(err);
        }
        res.send(result);
    });
});

当我试图通过点击路由器指示的 URL 来测试它时,它只是无限期地加载。

我知道我上面的内容是错误的,因为我从未编写过需要回调的函数。但是,当我尝试弄清楚如何重写它时,我真的很困惑——我该如何编写我的函数以在其中发生异步事件时进行回调?

有人可以帮我重写我的函数以正确使用回调,这样当我实际使用该函数时,我仍然可以使用异步响应吗?

您使用路由器文件中的 db.fa,并将第二个参数作为回调函数传递。但是函数签名没有 cb 参数,也没有使用它。

主要思想 - 您尝试启动一个异步操作,但不知道它何时结束,所以您向它发送一个回调函数,以便在所有操作完成时触发。

固定代码应该是这样的:

//Module 1
//Module 1 has 2 functions, both are necessary to properly format
function fnA(param1, cb1){
    db.cypherQuery(query, function(err, result){
        if(err){
            cb1(err); <-- return error to original call
        }
        var reformattedData = {};
        //code that begins storing re-formatted data in reformattedData

        //the function that handles the rest of the formatting
        fnB(param1, param2, cb1);
    });
});

function fnB(param1, reformattedData, cb1){
    db.cypherQuery(query, function(err, result){
        if(err){
            cb1(err); <-- return error to original call
        }
        //the rest of the reformatting that uses bits from the second query 
        cb1(false, dataObjectToSendBack); <--- This will call the anonymouse function in your router call
    });
});

exports.fnA = fnA;

路由器文件:

var db = require('module1');

router.get('/url', function(req,res,next){
    db.fnA(param1, function(err, result){ <-- This anonymous function get triggered last 
        if (err){
            return next(err);
        }
        res.send(result);
    });
});