Node.js:异步回调混淆

Node.js: Asynchronous callback confusion

本文关键字:回调 异步 js Node      更新时间:2023-09-26

我正试图弄清楚如何为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);
    });
});