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);
});
});
相关文章:
- Meteor:异步回调问题
- Meteor:异步函数回调异常:onAfterAction
- 异步中的回调函数出现问题'张贴'
- JavaScript中的异步回调
- 如何将此异步回调转换为生成器
- 在Nodejs中堆叠异步回调事件的最佳方式
- 如何使用jQuery等待来自回调的异步调用
- 从异步回调中获取值
- jasmine 2-在jasmine指定的超时时间内未调用异步回调.DEFAULT_TIMEOUT_INTERVAL
- 将数据注入异步回调(使用 node.js)
- 由于异步回调,变量被覆盖
- 与 promise 一起使用时,异步瀑布不执行下一个回调方法
- 如何将状态对象/数据传递给(异步)ajax 回调
- 管理Meteor中的异步回调
- 如何通过一个回调异步排队和执行多个promise
- 如何等到异步回调完成后才能使用检索到的数据
- 如何在node.js中通过API回调异步递归
- 将数据传递给node.js回调——异步问题
- 从回调(异步方法)内部访问对象文字属性
- 使 JavaScript 函数与回调异步