没有结果的异步查找挂起应用程序

Async lookup without results hangs app

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

下面是一些示例控制器代码,使用 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'?

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);
        }

    });
};