【发布时间】:2015-02-11 19:31:46
【问题描述】:
我正在尝试弄清楚如何为 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 来测试它时,它只是无限期地加载。
我知道我上面的内容是错误的,因为我从未编写过需要回调的函数。但是,当我尝试弄清楚如何重写它时,我真的很困惑-如何编写函数以在其中发生异步内容时进行回调?
有人可以帮我重写我的函数以正确使用回调,这样当我实际使用该函数时,我仍然可以使用异步响应吗?
【问题讨论】:
标签: javascript node.js asynchronous callback