简体   繁体   English

我的回调函数不起作用

[英]My callback function not working

I am do a nodeJS application, in which there is a call back function to persist the value to the database( MongoDB ). 我正在做一个nodeJS应用程序,其中有一个回调函数来将值持久保存到数据库( MongoDB )。 The callback function as below: 回调函数如下:

exports.add = function(student, cb) {
    var collection = db.get().collection('students');
    collection.insert(student, function(err) {
        if (err) {
           throw err;
        }
        console.log("Record added");
    });
}

The above call back function is called from the another fuction as below: 上面的回调函数是从另一个函数调用的,如下所示:

router.post("/add", function(req,res){
    var student = req.body;
    Students.add(student, function(err) {
        if (err) {
            throw err;
        }
        var respOut = JSON.stringify({id:student.id});
        console.log("respOut");
        res.send(respOut);
    });
});

The call back function is called from the above bolded(Students.add) section. 从上面的粗体(Students.add)部分调用该回调函数。 Currently I am able to persist the data on to the DB. 目前,我能够将数据持久保存到数据库中。 But not getting any output on the console( given console out as -> console.log("respOut"); or any response in the UI(from above code). Is there any problem with my call back function? or I am missing anything? 但是没有在控制台上获得任何输出(给控制台以-> console.log("respOut");或者在UI中没有任何响应(来自上述代码)。我的回调函数是否有问题?还是我丢失了有什么事吗

You're not using cb in your Students.add method. 您没有在Students.add方法中使用cb

The easiest would be to just pass the callback through to collection.insert : 最简单的方法是将回调传递给collection.insert

exports.add = function(student, cb) {
    var collection = db.get().collection('students');
    collection.insert(student, cb);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM