【问题标题】:Async lookup without results hangs app没有结果的异步查找挂起应用程序
【发布时间】:2015-02-02 03:42:48
【问题描述】:

我正在尝试将 mongoose 与异步一起使用,大部分情况下一切正常...但是当我执行不返回任何结果的查找时,我的应用程序似乎挂起并最终超时。

这是一些示例控制器代码,它使用 mongoose 和 async 按 id 进行简单查找:

module.exports.find = function(req, res) {
    async.waterfall([
        function(next) {
            SomeModel.findById(req.params.id, next);
        },
        function(someModel, next) {
            if (!SomeModel) {
                res.status(404).json({
                    success: false,
                    message: 'SomeModel not found'
                });
            } else {
                res.json(SomeModel);
            }
        }
    ]);
};

如果找到一条记录,一切都会恢复正常,但是对于不存在的 id,似乎永远不会调用第二个异步步骤,最终整个请求都会超时。

那么我在这里做错了什么?即使没有找到记录,如何让 'findById' 方法调用 'next'?

【问题讨论】:

    标签: javascript node.js mongodb asynchronous


    【解决方案1】:

    Mongoose 抛出一个错误,而你没有发现它。我应该提到的另一件事是您应该在最终回调中进行响应处理(您尚未定义)。

    试试这样的:

    module.exports.find = function(req, res) {
        async.waterfall([
            function(next) {
                SomeModel.findById(req.params.id, next);
            }
        ], function(err, SomeModel){
            // this is the final callback
    
            if (err) {
                // put error handling here 
                console.log(err)
            }
    
            if (!SomeModel) {
                res.status(404).json({
                    success: false,
                    message: 'SomeModel not found'
                });
    
            } else {
                res.json(SomeModel);
            }
    
        });
    };
    

    或者,您可以将其简化为不使用瀑布:

    module.exports.find = function(req, res) {
        SomeModel.findById(req.params.id, function(err, SomeModel){
            if (err) {
                // put error handling here 
                console.log(err)
            }
    
            if (!SomeModel) {
                res.status(404).json({
                    success: false,
                    message: 'SomeModel not found'
                });
    
            } else {
                res.json(SomeModel);
            }
    
        });
    };
    

    【讨论】:

    • 我担心这就是答案!感谢您为我解决这个问题。出于某种原因,我认为 Async 会为我处理错误,这不是使用它的原因之一吗?
    • 就错误处理而言,异步在某些方面有所帮助,但绝对不能完全处理它们。
    猜你喜欢
    • 1970-01-01
    • 2018-06-27
    • 2018-09-02
    • 2015-04-09
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多