【问题标题】:how to call wait until function is executed in node js如何在节点js中调用等待直到函数执行
【发布时间】:2016-12-02 17:07:19
【问题描述】:

我已经编写了一个函数,它使用 mongoose 删除 mongodb 中的数据并保存在单独的文件夹 DB.js 中,代码如下所示

delete_user : function(data) {
    connection.findOne({email:data}, function(err, result) {
        connection.findById(result.id, function(err, val) { 
            if(err) {
                throw err;
            }
            connection .findByIdAndRemove(val.id, function(err) {
                    if(err) {
                        throw err;
                    }
            });
        });
    });
},

连接mongodb所需的连接写在其他文件中

在测试文件(用mocha框架编写)中,我需要该文件并调用此函数

after('Flust out the created user', function(done) {
    Db.delete_user(req_body.email);
    console.log("User "+req_body.email+" deleted");
    done();
})

相同的代码用于两个不同的测试文件 a.test.js 和 b.test.js

当我使用 mocha 运行测试文件时

它会抛出错误

Error: timeout of 10000ms exceeded. Ensure the done() callback is being called in this test.

从文件 a.test.js 创建的用户在数据库中被删除 从文件 b.test.js 创建的用户不会被删除并抛出错误

【问题讨论】:

  • 我不知道你在问什么。如果您想知道delete_user() 何时完成,您需要向其中传递一个回调,该回调将在完成时调用。

标签: node.js async-await mocha.js


【解决方案1】:

在你的函数中添加回调:

delete_user : function(data, callback) {
connection.findOne({email:data}, function(err, result) {
    connection.findById(result.id, function(err, val) { 
        if(err) {
            throw err;
        }
        connection .findByIdAndRemove(val.id, function(err) {
                if(err) {
                    throw err;
                }
                return callback();
        });
    });
});
},

然后:

after('Flust out the created user', function(done) {
    Db.delete_user(req_body.email, function(){
        console.log("User "+req_body.email+" deleted");
        done();
    });
 })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    相关资源
    最近更新 更多