Node.js 未处理的承诺拒绝

Node.js Unhandled promise rejection

我正在尝试使用 passport 通过 node.js 进行登录,但是当不在数据库中的用户名尝试登录时我遇到了问题。我收到以下错误 (node:9708) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: deferred.resolve is not a function.

登录函数:

exports.login = function(username, password) {
    var deferred = Q.defer;

    MongoClient.connect(mongodbUrl, function(err, db) {
        var collection = db.collection('users');

        collection.findOne({'username' : username}).then(function(result) {
            if (result === null) {
                console.log('User not found:', username);
                deferred.resolve(false);
            } else {
                var hash = result.password;
                console.log('User found:', username);

                if (bcrypt.compareSync(password, hash)) {
                    deferred.resolve(result);
                } else {
                    console.log('Authentication for ' + username + 'failed');
                    deferred.resolve(false);
                }
            }

            db.close();
        });
    }).catch(err => console.log(err));

    return deferred.promise;
};

Passport.use 函数:

passport.use('local-signin', new LocalStrategy({passReqToCallback : true}, function(req, username, password, done) {
    funct.login(username, password).then(function(user) {
        if (user) {
            console.log(user.username + 'logged in');
            req.session.success = 'Welcome, ' + user.username + '!';
            done(null, user);
        }

        if (!user) {
            console.log('Failed login attempt');
            req.session.error = 'Your Password or Username is incorrect! Please try again.';
            done(null, user);
        }
    }).fail(function(err) {
        console.log(err.body);
    });
}));

可以解决或拒绝承诺。您必须针对这两种情况进行编程。像这样在代码末尾添加一个 .catch:

collection.findOne({'username' : username}).then().catch(err => console.log(err))