回调不是使用节点js的异步模块的mongodb查询中的函数

问题描述 投票:0回答:1

我试图在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)。该错误的原因是什么,函数设置错误还是执行错误?

node.js mongodb asynchronous async.js
1个回答
0
投票

如果我已经理解您的问题(尽管缺少很多代码来理解该问题),这是错误的:

function(res,callback){                             // function signature

query[item.action](req, res, resp, (err, data)=>{   // function call

它们根本不匹配,您将res传递为callback,并且在内部函数中将callback(实际上是res)用作函数。

© www.soinside.com 2019 - 2024. All rights reserved.