运行Async函数的函数是否被认为是Async本身?以及如何处理其错误?

时间:2016-09-23 14:08:26

标签: node.js asynchronous mongoose

所以我有一个运行其他异步函数的函数,我想知道处理错误的最佳方法是什么,如果我这样做的话,#34;正确的方式&#34 ;

基本上这个功能的作用是:

  1. 收到"模型名称",一个具有要传递给架构的属性的对象和一个回调函数(我不知道我是否需要,或者是最佳实践这种情况)。

  2. 然后我检查输入(查看注释),在一种情况下我使用文件系统模块(Async),因为我只想在需要时才需要模型。

  3. 之后,我尝试将它全部保存到数据库中,这也是异步的。

  4. 快速说明:我使用Mongoose来处理数据库。

    / * *用于向数据库添加新条目的功能。 *此功能取决于各种异步功能, *所以我们希望收到一个回调函数,以便更好地处理错误。 * *期待: * modelName =要使用的模型的名称。 * properties =要传递给模型架构的对象。 *回调=上面解释过。 * / function add(modelName,properties,callback){

    // If a callback wasn't passed, throw error.
    if (typeof callback !== 'function') {
        return callback(new Error('Model Add function should receive a callback'));
    }
    
    /*
    * The variable 'properties' is not required, so only if declared
    * we'll check if it is an object.
    * IMPORTANT: Needs to be fixed!
    */
    if (typeof properties !== 'object') {
        return callback(new Error('Properties passed should be an Object'));
    }
    
    /*
    * Checking modelName is an existing model by checking if a file with that
    * name exists in the models directory.
    *
    * This is an asynchronous so we handle the output(which can result in an error)
    * using a callback.
    */
    fs.access(`./models/${modelName.toLowerCase()}.js`, fs.constants.F_OK, err => {
    
        // If an error is returned it means that the file does not exists.
        if (err) {
            return callback(new Error(`There is no Model "${modelName}"`));
        }
    
        // Require the model file.
        require(`./${modelName.toLowerCase()}`);
    
        // Getting the model.
        let Model = mongoose.model(modelName);
        let document = new Model(properties);
    
        // Saving the new "document" to the database.
        document.save(err => {
            if (err) {
                return callback(new Error(`Error while saving "${modelName}" to the Database: ${err}`));
            }
    
            // For debugging purposes...
            console.log(`A new ${modelName} was successfully saved to the database`);
        });
    
    });
    

    }

    正如你所看到的,我在这里嵌套了异步函数,我觉得它可以做得更好。

    有什么想法吗?这是处理数据库任务的正确方法吗?

    向前谢谢!

1 个答案:

答案 0 :(得分:1)

我注意到的一些事情:

if (typeof callback !== 'function') {
    return callback(new Error('Model Add function should receive a callback'));
}

你怎么称呼回叫说没有回叫?

// Require the model file.
require(`./${modelName.toLowerCase()}`);

require() 同步 - 永远不要在异步函数中调用它。它可能会被缓存,只会在第一次调用时阻塞(对于每个模型),但它会阻止整个服务器。

无论如何,这个问题可能更适合https://codereview.stackexchange.com/