Express.js中的自定义回调获取 [英] Custom callback in Express.js get
本文介绍了Express.js中的自定义回调获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的app.js中有问题
I have a get in my app.js
app.get('/api/personnel', api.personnel);
调用此函数作为回调以从mongo加载一些数据:
that calls this function as a callback to load some data from mongo:
exports.personnel = function(req, res) {
var docs;
db.personnel.find(function(err, docs) {
if (err) {
logError(err);
} else {
res.json({
personnel: docs
});
}
});
};
那很好,但是我真的很希望能够在函数完成后调用回调进行测试:
That works just fine, but I'd really like to be able to call a callback for testing purposes when the function is complete:
exports.personnel = function(req, res, callback) {
var docs;
db.personnel.find(function(err, docs) {
if (err) {
logError(err);
} else {
res.json({
personnel: docs
});
}
callback();
});
从实时应用程序中调用该函数时,
callback()
为空,并给我一个错误:
callback()
is empty when the function is called from the live application and gives me a error:
Error: Can't set headers after they are sent.
我该如何让get呼叫我的回调?
How do I go about having a get call my callback?
推荐答案
您只需包装该函数即可插入其他函数参数:
You can just wrap that function to insert the additional function argument:
exports.personnel = function(req, res, callback) {
var docs;
db.personnel.find(function(err, docs) {
if (err) {
logError(err);
} else {
res.json({
personnel: docs
});
}
});
///////////////////////////////////////////////////
var callback = ...;
pp.get('/api/personnel', function(req, res) {
api.personnel(req, res, callback);
});
这篇关于Express.js中的自定义回调获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文