我试图在async each循环中调用从另一个文件导出的函数,在该循环中,它迭代传入数据的数组并相应地执行查询,如下所示:
const query = require('./queries')
function receive(req,resp ,doneFunc){
const listData = [];
let checkedList = req.body.checkedList
async.each(checkedList, (item, next)=>{
//Every iteration gets a parameter called action from an object inside the array which is the
//name of the function needed
//
query[item.action](req, res, resp, (err, data)=>{
listData.push(data);
if(listData.length === checkedList.length)doneFunc(listData);
next();
});
}, err=>{
console.log(err);
});
}
在query[item.action]
中调用的函数具有以下结构
exports.any = function(res,callback){
MongoClient.connect(url,function (err, client) {
let dbo = client.db("DB")
if(!err) {
dbo.collection("collection",function(err ,coll){
coll.aggregate([
//make aggregation
]).toArray(function(err,data){
//execute callback when the aggregation has finished , this is where the error ocurrs
if(!err) return callback(null,data)
return callback(err,null)
})
})
} else {
return callback(err,null);
}
});
}
当async.each循环的执行到达query的调用时,它返回消息
TypeError: callback is not a function
at ...\server\routes\queries.js:385:37
应该在其中执行return callback(null,data)。该错误的原因是什么,函数设置错误还是执行错误?
如果我已经理解您的问题(尽管缺少很多代码来理解该问题),这是错误的:
function(res,callback){ // function signature
query[item.action](req, res, resp, (err, data)=>{ // function call
它们根本不匹配,您将res
传递为callback
,并且在内部函数中将callback
(实际上是res
)用作函数。